首页 > 代码库 > 419. Battleships in a Board

419. Battleships in a Board

简化版的number of island,noi是四个方向的,这个是两个方向的

 

 1     public int countBattleships(char[][] board) {
 2         if(board.length == 0 || board[0].length == 0) {
 3             return 0;
 4         }
 5         int row = board.length;
 6         int col = board[0].length;
 7         int cnt = 0;
 8         boolean[][] visited = new boolean[row][col];
 9         for(int i = 0; i < row; i++) {
10             for(int j = 0; j < col; j++) {
11                 if(!visited[i][j] && board[i][j] == ‘X‘) {
12                     cnt++;
13                     explore(board, visited, i, j);
14                 }
15             }
16         }
17         return cnt;
18     }
19     
20     private final static int[][] dirs = {{1, 0}, {0, 1}};
21     
22     private void explore(char[][] board, boolean[][] visited, int i, int j) {
23         visited[i][j] = true;
24         for(int[] dir: dirs) {
25             int x = i + dir[0];
26             int y = j + dir[1];
27             if(x >= board.length || y >= board[0].length || board[x][y] == ‘.‘) {
28                 continue;
29             }
30             explore(board, visited, x, y);
31         }
32     }

 

419. Battleships in a Board