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

Number of Islands

时间:2015-04-24 12:14:49      阅读:143      评论:0      收藏:0      [点我收藏+]

标签:

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

解题思路:

这题和 Surrounded Regions 一模一样,都是图的BFS操作。

如果上下左右是1,就往那个方向拓展,直到BFS结束。一次BFS就是一个island。

这题比 Surrounded Regions 更简单,还没有回写的操作。

代码如下

public class Solution {
    public int numIslands(char[][] grid) {
        if(grid.length == 0) {
            return 0;
        }
        
        int result = 0;
        //记录已经遍历过的格子
        int[][] visited = new int[grid.length][grid[0].length];
        //queue的成员是一个{i,j}的数组,记录本次BFS的坐标
        Queue<int []> queue = new LinkedList<int []>();
        
        for(int i = 0; i < grid.length; i++) {
            for(int j = 0; j < grid[0].length; j++) {
                if(grid[i][j] == ‘1‘ && visited[i][j] == 0) {
                    queue.offer(new int[]{i, j});
                    visited[i][j] = 1;
                    // 一个while就是一次bfs,即一个island
                    while(queue.size() > 0) {
                        int[] index = queue.poll();
                        if(index[0] > 0 && grid[index[0] - 1][index[1]] == ‘1‘ && visited[index[0] - 1][index[1]] == 0) {
                            queue.offer(new int[]{index[0] - 1, index[1]});
                            visited[index[0] - 1][index[1]] = 1;
                        }
                        if(index[1] > 0 && grid[index[0]][index[1] - 1] == ‘1‘ && visited[index[0]][index[1] - 1] == 0) {
                            queue.offer(new int[]{index[0], index[1] - 1});
                            visited[index[0]][index[1] - 1] = 1;
                        }
                        if(index[0] < grid.length - 1 && grid[index[0] + 1][index[1]] == ‘1‘ && visited[index[0] + 1][index[1]] == 0) {
                            queue.offer(new int[]{index[0] + 1, index[1]});
                            visited[index[0] + 1][index[1]] = 1;
                        }
                        if(index[1] < grid[0].length - 1 && grid[index[0]][index[1] + 1] == ‘1‘ && visited[index[0]][index[1] + 1] == 0) {
                            queue.offer(new int[]{index[0] , index[1] + 1});
                            visited[index[0]][index[1] + 1] = 1;
                        }
                    }
                    // 一次bfs结束,island数量+1
                    result++;
                }
            }
        }
        return result;
    }
}

 

Number of Islands

标签:

原文地址:http://www.cnblogs.com/NickyYe/p/4452901.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!