首页 > 代码库 > 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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。