ARTICLE DETAIL

建站实战干货

来自一线的建站与推广经验沉淀,每一条都经过真实交付验证。

LeetCode200. Number of Islands——DFS

2026/9/28 3:27:46 拓冰建站 浏览量
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>>& grid,vector<vector<bool>>& 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 >= grid.size() || nextY < 0 || nextY >= grid[0].size()) continue;if(!visited[nextX][nextY] && grid[nextX][nextY] == '1'){visited[nextX][nextY] = true;dfs(grid,visited,nextX,nextY);}}}int numIslands(vector<vector<char>>& 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' && !visited[i][j]){res++;visited[i][j] = true;dfs(grid,visited,i,j);}}}return res;}
};