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

[LeetCode] Number of Islands

时间:2015-04-09 23:51:43      阅读:223      评论:0      收藏:0      [点我收藏+]

标签:c++   leetcode   

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

标签:c++   leetcode   

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

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