首页 > 其他 > 详细

Leetcode: Number of Islands

时间:2015-04-11 06:33:33      阅读:253      评论:0      收藏:0      [点我收藏+]
Given a 2d grid map of ‘1‘s (land) and ‘0‘s (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.

Example 1:

11110
11010
11000
00000
Answer: 1

Example 2:

11000
11000
00100
00011
Answer: 3

DFS的Flood Fill方法,

使用额外Visited数组的做法:

 1 public class Solution {
 2     public int numIslands(char[][] grid) {
 3         if (grid==null || grid.length==0 || grid[0].length==0) return 0;
 4         int count = 0;
 5         boolean[][] visited = new boolean[grid.length][grid[0].length];
 6         for (int i=0; i<grid.length; i++) {
 7             for (int j=0; j<grid[0].length; j++) {
 8                 if (grid[i][j] != ‘1‘) continue;
 9                 else {
10                     count++;
11                     floodFill(grid, i, j, visited);
12                 }
13             }
14         }
15         return count;
16     }
17     
18     public void floodFill(char[][] grid, int i, int j, boolean[][] visited) {
19         if (i<0 || i>=grid.length || j<0 || j>=grid[0].length) return;
20         if (visited[i][j]) return;
21         if (grid[i][j] != ‘1‘) return;
22         grid[i][j] = ‘2‘;
23         floodFill(grid, i-1, j, visited);
24         floodFill(grid, i+1, j, visited);
25         floodFill(grid, i, j-1, visited);
26         floodFill(grid, i, j+1, visited);
27     }
28 }

更节省空间的方法:不使用额外visited数组,但是用‘1’变成‘2’表示visited的方法

 1 public class Solution {
 2     public int numIslands(char[][] grid) {
 3         if (grid==null || grid.length==0 || grid[0].length==0) return 0;
 4         int count = 0;
 5         for (int i=0; i<grid.length; i++) {
 6             for (int j=0; j<grid[0].length; j++) {
 7                 if (grid[i][j] != ‘1‘) continue;
 8                 else {
 9                     count++;
10                     floodFill(grid, i, j);
11                 }
12             }
13         }
14         return count;
15     }
16     
17     public void floodFill(char[][] grid, int i, int j) {
18         if (i<0 || i>=grid.length || j<0 || j>=grid[0].length) return;
19         if (grid[i][j] != ‘1‘) return; //either 0(water) or 2(visited)
20         grid[i][j] = ‘2‘;
21         floodFill(grid, i-1, j);
22         floodFill(grid, i+1, j);
23         floodFill(grid, i, j-1);
24         floodFill(grid, i, j+1);
25     }
26 }

 

Leetcode: Number of Islands

原文:http://www.cnblogs.com/EdwardLiu/p/4416153.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!