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

[LeetCode] Number of Islands

时间:2017-10-10 14:43:04      阅读:165      评论:0      收藏:0      [点我收藏+]

标签:class   不用   count   void   public   vector   使用   利用   一个   

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

寻找岛屿的个数。核心思想是利用一个visited二维数组来标志一个数(1)是否被访问过。在grid二维数组中局部使用广度优先遍历来判断并寻找岛屿。如果访问过则下次就不用将其再次计算。

class Solution {
public:
    int numIslands(vector<vector<char>>& grid) {
        if (grid.empty() || grid[0].empty())
            return 0;
        int cnt = 0;
        const int M = grid.size();
        const int N = grid[0].size();
        vector<vector<bool>> visited(M, vector<bool>(N, false));
        for (int i = 0; i != M; i++) {
            for (int j = 0; j != N; j++) {
                if (!visited[i][j] && grid[i][j] == 1) {
                    numIslandsCore(grid, visited, i, j);
                    cnt++;
                }
            }
        }
        return cnt;
    }
    
    void numIslandsCore(vector<vector<char>>& grid, vector<vector<bool>>& visited, int i, int j) {
        if (i >= 0 && i < grid.size() && j >= 0 && j < grid[0].size() && !visited[i][j] && grid[i][j] == 1) {
            visited[i][j] = true;
            numIslandsCore(grid, visited, i - 1, j);
            numIslandsCore(grid, visited, i, j - 1);
            numIslandsCore(grid, visited, i, j + 1);
            numIslandsCore(grid, visited, i + 1, j);
        }
    }
};
// 6 ms

 

[LeetCode] Number of Islands

标签:class   不用   count   void   public   vector   使用   利用   一个   

原文地址:http://www.cnblogs.com/immjc/p/7645106.html

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