首页 > 其他 > 详细

200. Number of Islands

时间:2016-09-12 06:05:11      阅读:261      评论:0      收藏:0      [点我收藏+]

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);
    }

似的题目有:

 

200. Number of Islands

原文:http://www.cnblogs.com/renyualbert/p/5863344.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!