码迷,mamicode.com
首页 > 其他好文 > 详细

200. Number of Islands

时间:2016-09-12 06:05:34      阅读:158      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!