huimeich / leetcode-solution

0 stars 0 forks source link

200. Number of Islands #136

Open huimeich opened 8 years ago

huimeich commented 8 years ago

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

huimeich commented 8 years ago
public class Solution {
    public int numIslands(char[][] grid) {
        if (grid.length == 0) return 0;
        HashMap<Integer, ArrayList<Integer>> groupmap = new HashMap<Integer, ArrayList<Integer>>();
        HashMap<Integer, Integer> indexmap = new HashMap<Integer, Integer>();

        for (int i = 0; i < grid.length; i++){
            for (int j = 0; j < grid[0].length; j++) {
                if (grid[i][j] == '1') {
                    int index = i * grid[0].length + j;
                    indexmap.put(index, index);
                    ArrayList<Integer> indexs = new ArrayList<Integer>();
                    indexs.add(index);
                    groupmap.put(index, indexs);
                    if (indexmap.containsKey(index - grid[0].length)) {
                        mergeGroup(index, index - grid[0].length, groupmap, indexmap);
                    }
                    if (j > 0 && indexmap.containsKey(index - 1)) {
                        mergeGroup(index, index - 1, groupmap, indexmap);
                    }
                }
            }
        }
        return groupmap.size();
    }

    public void mergeGroup(int m1, int m2, HashMap<Integer,ArrayList<Integer>> groupmap, HashMap<Integer,Integer> indexmap) {
        if (!indexmap.containsKey(m1) || !indexmap.containsKey(m2) || indexmap.get(m1) == indexmap.get(m2)) return;
        ArrayList<Integer> indexs = groupmap.remove(indexmap.get(m2));
        groupmap.get(indexmap.get(m1)).addAll(indexs);
        for (Integer index : indexs) {
            indexmap.put(index, indexmap.get(m1));
        }
    }
}
huimeich commented 8 years ago
public class Solution {
    public int numIslands(char[][] grid) {
        int count = 0;
        for (int i = 0; i < grid.length; i++){
            for (int j = 0; j < grid[0].length; j++){
                if (grid[i][j] == '1'){
                    markNeighbor(grid, i, j);
                    count++;
                }
            }
        }
        return count;
    }
    public void markNeighbor(char[][] grid, int i, int j){
        if (i < 0 || j < 0 || i >= grid.length || j >= grid[0].length) return;
        if (grid[i][j] == '1') {
            grid[i][j] = '0';
            markNeighbor(grid, i - 1, j);
            markNeighbor(grid, i + 1, j);
            markNeighbor(grid, i, j - 1);
            markNeighbor(grid, i, j + 1);
        }
    }
}