题目地址:
https://leetcode.com/problems/battleships-in-a-board/
给定一个二维矩阵,含.
和X
两种字符。任何一个
1
×
N
1\times N
1×N或者
N
×
1
N\times 1
N×1的X
组成的行或列视为一个“战舰”。问一共有多少个战舰。题目保证战舰与战舰之间是有一个空行或者空列的。
思路是,只数战舰的最左上角的那个X
,其余的X
都略过。这样就能数出有多少个了。代码如下:
public class Solution {
public int countBattleships(char[][] board) {
if (board == null || board.length == 0 || board[0].length == 0) {
return 0;
}
int res = 0;
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[0].length; j++) {
if (board[i][j] == '.') {
continue;
}
if (i > 0 && board[i - 1][j] == 'X') {
continue;
}
if (j > 0 && board[i][j - 1] == 'X') {
continue;
}
res++;
}
}
return res;
}
}
时间复杂度 O ( m n ) O(mn) O(mn), m m m是行数, n n n是列数,空间 O ( 1 ) O(1) O(1)。