首页 > 其他 > 详细

[LeetCode] Number of Islands

时间:2015-04-09 23:49:19      阅读:206      评论:0      收藏:0      [点我收藏+]

Number of Islands

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

解题思路:
以前我做过这个题目,现在竟然全忘了,折腾了好久,看来每天都要保持锻炼啊。其实这道题思路挺简单的啊,就是递归标记而已。比如,若当前元素为‘1’,就递归将其左右上下为1的元素全部标记为‘0’,计数加1。(之前做的是积水,还包括对角处)。下面是代码;
class Solution {
public:
    int numIslands(vector<vector<char>> &grid) {
        int m = grid.size();
        if(m==0){
            return 0;
        }
        int n = grid[0].size();
        if(n==0){
            return 0;
        }
        
        int result = 0;
        for(int i=0; i<m; i++){
            for(int j=0; j<n; j++){
                if(grid[i][j] == '1'){
                    result++;
                    markRead(grid, m, n, i, j);
                }
            }
        }
        return result;
    }
    
    void markRead(vector<vector<char>> &grid, int m, int n, int i, int j){
        if(i<0||j<0 || i>=m||j>=n||grid[i][j]=='0'){
            return;
        }
        grid[i][j]='0';
        markRead(grid, m, n, i+1, j);
        markRead(grid, m, n, i, j+1);
        markRead(grid, m, n, i-1, j);
        markRead(grid, m, n, i, j-1);
    }
};


[LeetCode] Number of Islands

原文:http://blog.csdn.net/kangrydotnet/article/details/44966751

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