思路1:遍历数组并做标记
看到这道题很容易就想到,用一个标记数组,将遍历过的符合条件的军舰标记,然后扫描一遍,统计答案
class Solution {
int cnt;
int[][] book;
public int countBattleships(char[][] board) {
book = new int[board.length][board[0].length];
for(int i = 0; i < board.length; i++ ) {
for(int j = 0; j < board[0].length; j++ ){
if(board[i][j] == 'X' && book[i][j] == 0){
for(int k = i; k < board.length && board[k][j] == 'X'; k++ ) {
book[k][j] = 1;
}
for(int k = j; k < board[0].length && board[i][k] == 'X'; k++ ) {
book[i][k] = 1;
}
cnt++;
}
}
}
return cnt;
}
}
时间复杂度:O(m×n)
空间复杂度:O(m×n)
思路2:只统计起点
本来我以为今天的每日一题就这,但看了大佬的题解,就有一种豁然开朗的感觉。
对于每一个军舰,我们只需要统计它的起点即可,也就是,遍历数组时,当前遍历到 board[i][j] == ‘X’,如果board[i-1][j]和board[i][j-1]都不是 ‘X’ 那么他就是一个军舰的起点,那么我们让sum++,否则就不统计入答案。
class Solution {
int cnt;
public int countBattleships(char[][] board) {
for(int i = 0; i < board.length; i++ ) {
for(int j = 0; j < board[0].length; j++ ){
if(i > 0 && board[i-1][j] == 'X')continue;
if(j > 0 && board[i][j-1] == 'X')continue;
cnt += board[i][j] == 'X'? 1 : 0;
}
}
return cnt;
}
}
时间复杂度:O(m×n)
空间复杂度:O(1)
大佬还是大佬,自愧不如。