首页 > 代码库 > 200. Number of Islands

200. 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做法,建一个visited 二维数组记录‘1’是否被访问过。只有在没有访问过的‘1’的时候才将结果加1。

public int NumIslands(char[,] grid) {        int row = grid.GetLength(0);        int col = grid.GetLength(1);        var visited = new bool[row,col];        int res = 0;        for(int i = 0;i< row;i++)        {            for(int j =0;j< col;j++)            {                if(grid[i,j] == 1 && !visited[i,j])                {                   DFSMarkVisted(grid,i,j,visited);                   res++;                }            }        }        return res;    }        private void DFSMarkVisted (char[,] grid, int x, int y, bool[,] visited)    {        if(x < 0 || x>= grid.GetLength(0)) return;        if(y < 0 || y>= grid.GetLength(1)) return;                if(grid[x,y] != 1 || visited[x,y]) return;        visited[x,y] = true;        DFSMarkVisted(grid,x-1,y,visited);        DFSMarkVisted(grid,x+1,y,visited);        DFSMarkVisted(grid,x,y-1,visited);        DFSMarkVisted(grid,x,y+1,visited);    }

似的题目有:

(M) Surrounded Regions 
(M) Walls and Gates 
(H) Number of Islands II 
(M) Number of Connected Components in an Undirected Graph
 

200. Number of Islands