LeetCode-200.Number of Islands

来源:互联网 发布:日线里引用分时数据 编辑:程序博客网 时间:2024/05/23 13:55

https://leetcode.com/problems/number-of-islands/

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.

Example 1:

11110
11010
11000
00000

Answer: 1

Example 2:

11000
11000
00100
00011

Answer: 3


dfs:

public class Solution {    public int NumIslands(char[,] grid)     {        int res = 0;        int m = (int)grid.GetLongLength(0);        int n = (int)grid.GetLongLength(1);        for (int i =0; i < m; i++)        {            for (int j =0; j < n; j++)            {                if (grid[i, j] =='1')                {                    res++;                    dfs(grid, i, j);                }            }        }        return res;    }    private void dfs(char[,] grid, int i, int j)    {        int m = (int)grid.GetLongLength(0);        int n = (int)grid.GetLongLength(1);        if (i < 0 || j < 0 || i >= m || j >= n||grid[i,j]=='0')            return;        grid[i, j] = '0';        dfs(grid, i, j - 1);        dfs(grid, i - 1, j);        dfs(grid, i, j + 1);        dfs(grid, i + 1, j);    }}


0 0
原创粉丝点击