您的位置:首页 > 其它

【LeetCode】Number of Islands

2015-06-02 09:28 387 查看
Number of Islands

Total Accepted: 8945 Total Submissions: 41107 My Submissions Question Solution

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

Credits:

Special thanks to @mithmatt for adding this problem and creating all test cases.

【解题思路】

1、题目大意为,1代表岛屿,2代表水。如果岛屿水平或者垂直相连,算一个岛。求所给的二次矩阵中岛屿的个数。

2、典型BFS,遍历每一个点,判断其相邻的点是否为1,如果为1即认为是同一个岛。

3、遍历结束,count的个数即为岛屿的个数。

Java AC

public class Solution {
    private int stepArr[][] = {{0,1},{0,-1},{1,0},{-1,0}};
    private int visit[][];
    private int m, n;
    public int numIslands(char[][] grid) {
        if(grid == null || grid.length == 0){
            return 0;
        }
        int count = 0;
        m = grid.length;
        n = grid[0].length;
        visit = new int[m]
;
        for(int i = 0; i < m; i++){
            for(int j = 0; j < n; j++){
                if(grid[i][j] == '1' && visit[i][j] == 0){
                    bfs(grid, i, j);
                    count++;
                }
            }
        }
        return count;
    }
    
    private void bfs(char grid[][], int i, int j){
        Queue<Integer> queue = new LinkedList<Integer>(); 
        queue.add(i * n + j);
        while(!queue.isEmpty()){
            int num = queue.poll();
            int x = num / n;
            int y = num % n;
                        
            for(int k = 0; k < 4; k++){
                int newX = x + stepArr[k][0];
                int newY = y + stepArr[k][1];
                if(newX >= 0 && newX < m && newY >= 0 && newY < n
                        && grid[newX][newY] == '1' && visit[newX][newY] == 0 ){
                        queue.add(newX * n + newY);
                        visit[newX][newY] = 1;
                }
            }
        }
    }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: