题意:给定一个甲板,查看上边停了多少战舰
思路:遍历数组,遇到X查看它的左边和上边是否有X,如果没有结果++
思想:数组遍历
复杂度:时间O(n^2),空间O(1)
class Solution {
public int countBattleships(char[][] board) {
int res = 0;
int m = board.length;
if(m == 0)
return res;
int n = board[0].length;
for(int i=0;i<m;i++) {
for(int j=0;j<n;j++) {
if(board[i][j] == 'X') {
if((i-1<0 && j-1<0)
|| (j-1>=0 && i-1<0 && board[i][j-1] == '.')
|| (i-1>=0 && board[i-1][j] == '.' && j-1<0)
|| (i-1>=0 && j-1 >=0 && board[i-1][j] == '.' && board[i][j-1] == '.'))
res++;
}
}
}
return res;
}
}
网友评论