码迷,mamicode.com
首页 > 其他好文 > 详细

419. Battleships in a Board

时间:2016-10-24 09:35:26      阅读:150      评论:0      收藏:0      [点我收藏+]

标签:oar   div   count   row   color   ret   nbsp   bat   简化   

简化版的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

标签:oar   div   count   row   color   ret   nbsp   bat   简化   

原文地址:http://www.cnblogs.com/warmland/p/5991698.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!