Number [LeetCode] 0200. Number of Islands islands

topic

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.

Given a two-dimensional grid by a '1' (land) and '0' (water) composition, the number of islands is calculated. An island surrounded by water, and it is through the horizontal or vertical direction is connected to each adjacent land. You can assume that the water surrounding the four sides of the grid are.

Example 1:

Input:
11110
11010
11000
00000

Output: 1

Example 2:

Input:
11000
11000
00100
00011

Output: 3

A Solution

Ideas: two-dimensional array of elements traversed by the input encountered 1:00 unfold BFS search, and met with the next record node.

Reference: https://www.cnblogs.com/grandyang/p/4402656.html

#include <vector>
#include <queue>

using namespace std;

class Solution {
public:
    int numIslands(vector<vector<char>>& grid) {
        if (grid.empty() || grid[0].empty()) {
            return 0;
        }
        int n_row = grid.size();
        int n_col = grid[0].size();
        int res = 0;
        vector<vector<bool>> visited(n_row, vector<bool>(n_col));
        vector<int> dirX{-1, 0, 1, 0}, dirY{0, 1, 0, -1};
        
        for (int i = 0; i < n_row; i++) {
            for (int j = 0; j < n_col; j++) {
                if (grid[i][j] == '0' || visited[i][j])
                    continue;
                ++res;
                queue<int> q{{i * n_col + j}};
                while (!q.empty()) {
                    int t = q.front(); q.pop();
                    for (int k = 0; k < 4; k++) {
                        int x = t / n_col + dirX[k];
                        int y = t % n_col + dirY[k];
                        if (x < 0 || x >= n_row || y < 0 || y >= n_col || grid[x][y] == '0' || visited[x][y])
                            continue;
                        visited[x][y] = true;
                        q.push(x * n_col + y);
                    }
                }
            }
        }
        return res;
    }
};

Guess you like

Origin www.cnblogs.com/bingmang/p/11408319.html