419. Battleships in a Board
Posted warmland
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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的主要内容,如果未能解决你的问题,请参考以下文章
[leetcode-419-Battleships in a Board]