本文介绍: 【代码】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;
    }
};

原文地址:https://blog.csdn.net/weixin_46841376/article/details/134721988

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任

如若转载,请注明出处:http://www.7code.cn/show_20770.html

如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱suwngjj01@126.com进行投诉反馈,一经查实,立即删除

发表回复

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