每日一题:419. 甲板上的战舰
作者:互联网
解题思路
类似于岛屿数量问题,只需要在图中找出练成一片的X即可
代码
class Solution {
int[][] dir = {{-1,0},{1,0},{0,-1},{0,1}};
public int countBattleships(char[][] board) {
int res = 0;
for (int i=0;i<board.length;i++){
for (int j=0;j<board[i].length;j++){
if (board[i][j] == 'X'){
res++;
dfs(i,j,board);
}
}
}
return res;
}
public void dfs(int x,int y,char[][] board){
board[x][y] = '.';
for (int i=0;i<dir.length;i++){
if (x+dir[i][0]>=0 && dir[i][0]+x<board.length && y+dir[i][1]>=0 && y+dir[i][1]<board[0].length && board[x+dir[i][0]][y+dir[i][1]]=='X'){
dfs(x+dir[i][0],y+dir[i][1],board);
}
}
}
}
标签:int,res,甲板,dfs,char,board,战舰,419,dir 来源: https://blog.csdn.net/weixin_45221477/article/details/122008844