Leetcode-200(Java) 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

传送门:https://leetcode.com/problems/number-of-islands/

 

public class Solution {
    public int numIslands(char[][] grid)
    {
        int cnt = 0;
        for(int x = 0; x < grid.length; x++)
        {
            for(int y = 0; y < grid[0].length; y++)
            {
                if(grid[x][y] == '1')
                {
                    this.BFS(grid, x, y);
                    cnt++;
                }
            }
        }
        return cnt;
    }
    
    private void BFS(char[][] grid, int x, int y)
    {
        if(x < 0 || x >= grid.length || y < 0 || y >= grid[0].length || grid[x][y] != '1')
            return;
        grid[x][y] = '0'; //被遍历到的点标记为0
        BFS(grid, x - 1, y);
        BFS(grid, x, y - 1);
        BFS(grid, x + 1, y);
        BFS(grid, x, y + 1);
    }
}

 

posted @ 2015-08-03 16:06  zetrov  阅读(460)  评论(0编辑  收藏  举报