本文介绍: 【代码】LeetCode200. Number of Islands——DFS。

一、题目

Given an m x n 2D binary grid grid which represents a map of ‘1’s (land) and ‘0’s (water), return 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:

Input: grid = [
[“1”,“1”,“1”,“1”,“0”],
[“1”,“1”,“0”,“1”,“0”],
[“1”,“1”,“0”,“0”,“0”],
[“0”,“0”,“0”,“0”,“0”]
]
Output: 1
Example 2:

Input: grid = [
[“1”,“1”,“0”,“0”,“0”],
[“1”,“1”,“0”,“0”,“0”],
[“0”,“0”,“1”,“0”,“0”],
[“0”,“0”,“0”,“1”,“1”]
]
Output: 3

Constraints:

m == grid.length
n == grid[i].length
1 <= m, n <= 300
grid[i][j] is ‘0’ or ‘1’.

二、题解

class Solution {
public:
    int dirs[4][2] = {0,1,1,0,-1,0,0,-1};
    void dfs(vector<vector<char&gt;&gt;&amp; grid,vector<vector<bool&gt;&gt;&amp; visited,int x,int y){
        for(int i = 0;i < 4;i++){
            int nextX = x + dirs[i][0];
            int nextY = y + dirs[i][1];
            if(nextX < 0 || nextX &gt;= grid.size() || nextY < 0 || nextY >= grid[0].size()) continue;
            if(!visited[nextX][nextY] &amp;&amp; grid[nextX][nextY] == '1'){
                visited[nextX][nextY] = true;
                dfs(grid,visited,nextX,nextY);
            }
        }
    }
    int numIslands(vector<vector<char>>&amp; grid) {
        int m = grid.size();
        int n = grid[0].size();
        vector<vector<bool>> visited(m,vector<bool>(n,false));
        int res = 0;
        for(int i = 0;i < m;i++){
            for(int j = 0;j < n;j++){
                if(grid[i][j] == '1' &amp;&amp; !visited[i][j]){
                    res++;
                    visited[i][j] = true;
                    dfs(grid,visited,i,j);
                }
            }
        }
        return res;
    }
};

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注