ARTICLE DETAIL

资讯详情

深耕网站建设、视觉设计与SEO优化的一线实战洞察。

LeetCode200. Number of Islands——DFS

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;}
};
返回列表