IncredibleThings

导航

LeetCode – Number of Islands

Given a 2-d 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

The basic idea of the following solution is merging adjacent lands, and the merging should be done recursively.

1. DFS

public int numIslands(char[][] grid) {
    if(grid==null || grid.length==0||grid[0].length==0)
        return 0;
 
    int m = grid.length;
    int n = grid[0].length;
 
    int count=0;
    for(int i=0; i<m; i++){
        for(int j=0; j<n; j++){
            if(grid[i][j]=='1'){
                count++;
                merge(grid, i, j);
            }
        }
    }
 
    return count;
}
 
public void merge(char[][] grid, int i, int j){
    int m=grid.length;
    int n=grid[0].length;
 
    if(i<0||i>=m||j<0||j>=n||grid[i][j]!='1')
        return;
 
    grid[i][j]='X';
 
    merge(grid, i-1, j);
    merge(grid, i+1, j);
    merge(grid, i, j-1);
    merge(grid, i, j+1);
}

 

二刷:

注意在变‘1’为‘2’的时候要判断当前值是否为‘1’用来减少memory消耗

class Solution {
    public int numIslands(char[][] grid) {
        int row = grid.length;
        if(row == 0){
            return 0;
        }
        int col = grid[0].length;
        int count = 0;
        Queue<Integer[]> queue = new LinkedList<>();
        for(int i=0; i<row; i++){
            for(int j = 0; j<col; j++){
                if(grid[i][j] == '1'){
                    count++;
                    Integer[] indexs = {i,j};
                    queue.offer(indexs);
                    while(!queue.isEmpty()){
                        Integer[] temp = queue.poll();
                        int m = temp[0]; int n = temp[1];
                        if(grid[m][n] == '1'){
                            grid[m][n]='2';
                            if(m-1 >= 0 && grid[m-1][n]=='1'){
                                Integer[] index = {m-1,n};
                                queue.offer(index);
                            }
                            if(m+1<row&&grid[m+1][n]=='1'){
                                Integer[] index = {m+1,n};
                                queue.offer(index);
                            }
                            if(n-1>=0&&grid[m][n-1]=='1'){
                                Integer[] index = {m,n-1};
                                queue.offer(index);
                            }
                            if(n+1<col&&grid[m][n+1]=='1'){
                                Integer[] index = {m,n+1};
                                queue.offer(index);
                            }
                        }
                    }
                }
            }
        }
        return count;
    }
}

 

posted on 2018-06-06 09:42  IncredibleThings  阅读(106)  评论(0)    收藏  举报