设为首页 加入收藏

TOP

leetcode 200 : Number of Islands
2015-11-21 01:01:30 来源: 作者: 【 】 浏览:2
Tags:leetcode 200 Number Islands

Number of Islands

Total Accepted: 8305 Total Submissions: 38192

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

[思路]

这道题有点像 word search的简化版. 每遇到'1'后, 开始向四个方向 递归搜索. 搜到后变为'0', 因为相邻的属于一个island. 然后开始继续找下一个'1'.

[CODE]

?

public class Solution {
    public int numIslands(char[][] grid) {
        int count = 0;
        for(int i=0; i
  
   =grid.length || y<0 || y>=grid[0].length || grid[x][y]!='1') return;
        grid[x][y] = '0';
        search(grid, x-1, y);
        search(grid, x+1, y);
        search(grid, x, y-1);
        search(grid, x, y+1);
    }
}
  


?

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇sgu-250 Constructive Plan 下一篇C++对象模型之简述C++对象的内存..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: