一、题目
1、题目描述
给你一个大小为
m x n
的矩阵board
表示甲板,其中,每个单元格可以是一艘战舰'X'
或者是一个空位'.'
,返回在甲板board
上放置的 战舰 的数量。战舰 只能水平或者垂直放置在
board
上。换句话说,战舰只能按1 x k
(1
行,k
列)或k x 1
(k
行,1
列)的形状建造,其中k
可以是任意大小。两艘战舰之间至少有一个水平或垂直的空位分隔 (即没有相邻的战舰)。
2、接口描述
python3
class Solution:
def countBattleships(self, board: List[List[str]]) -> int:
cpp
class Solution {
public:
int countBattleships(vector<vector<char>>& board) {
}
};
js
/**
* @param {character[][]} board
* @return {number}
*/
var countBattleships = function(board) {
};
php
class Solution {
/**
* @param String[][] $board
* @return Integer
*/
function countBattleships($board) {
}
}
3、原题链接
二、解题报告
1、思路分析
即计算连通块个数
网格上如果只是计算连通块个数,我们只需找到多少个方格满足左边和上边都不是'X'
2、复杂度
时间复杂度: O(NM)空间复杂度:O(1)
3、代码详解
python3
class Solution:
def countBattleships(self, board: List[List[str]]) -> int:
cnt = 0
m, n = len(board), len(board[0])
for i in range(m):
for j in range(n):
if board[i][j] == 'X' and (not i or board[i - 1][j] != 'X') and (not j or board[i][j - 1] != 'X'):
cnt += 1
return cnt
cpp
class Solution {
public:
int countBattleships(vector<vector<char>>& board) {
int m = board.size(), n = board[0].size(), cnt = 0;
for (int i = 0; i < m; i ++ )
for (int j = 0; j < n; j ++ )
if (board[i][j] == 'X' && (!i || board[i - 1][j] != 'X') && (!j || board[i][j - 1] != 'X'))
++ cnt;
return cnt;
}
};
js
/**
* @param {character[][]} board
* @return {number}
*/
var countBattleships = function(board) {
let m = board.length, n = board[0].length, cnt = 0;
for (let i = 0; i < m; i ++ )
for (let j = 0; j < n; j ++ )
if (board[i][j] == 'X' && (!i || board[i - 1][j] != 'X') && (!j || board[i][j - 1] != 'X'))
++ cnt;
return cnt;
};
php
class Solution {
/**
* @param String[][] $board
* @return Integer
*/
function countBattleships($board) {
$m = count($board);
$n = count($board[0]);
$cnt = 0;
for ($i = 0; $i < $m; $i ++ )
for ($j = 0; $j < $n; $j ++ )
if ($board[$i][$j] == 'X' && (!$i || $board[$i - 1][$j] != 'X') && (!$j || $board[$i][$j - 1] != 'X'))
$cnt ++;
return $cnt;
}
}