classSolution {privatestaticint[][] DIRS = {{1,0}, {0,1}, {-1,0}, {0,-1}};publicintcountBattleships(char[][] board) {int m =board.length;int n = board[0].length;int count =0;for (int i =0; i < m; i++) {for (int j =0; j < n; j++) {if (board[i][j] =='X') {dfs(board, i, j); count++; } } }return count; }privatevoiddfs(char[][] board,int i,int j) {int m =board.length;int n = board[0].length;if (!(i >=0&& i < m && j >=0&& j < n) || board[i][j] !='X') {return; } board[i][j] ='.';for (int[] dir : DIRS) {dfs(board, i + dir[0], j + dir[1]); } }}
Follow up: Could you do it in one-pass, using only O(1) extra memory and without modifying the values board?
classSolution {publicintcountBattleships(char[][] board) {int m =board.length;int n = board[0].length;int count =0;for (int i =0; i < m; i++) {for (int j =0; j < n; j++) {// meets this condition, it must a head of a ship if (board[i][j] =='X'&& (i ==0|| board[i-1][j] =='.') && (j ==0|| board[i][j-1] =='.')) { count++; } } }return count; }}