Description

200. 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

Java DFS solution

TODO: try out a faster solution.

class Solution {
    private HashSet<Node> visited;
    private int ret = 0;
    private int n, m;
    public int numIslands(char[][] grid) {
        if (grid.length==0 || grid[0].length==0) return ret;
        n = grid.length;
        m = grid[0].length;
        visited = new HashSet<>();
        for (int i=0; i<n; i++) {
            for (int j=0; j<m; j++) {
                if (Node.isLand(i, j, grid)) {
                    Node curNode = Node.valueOf(i, j);
                    if (visited.add(curNode)) {
                        ret++;
                        dfs(curNode, grid);
                    } 
                }
                
            }
        }
        
        return ret;
    }
    
    private void dfs(Node node, char[][] grid) {
        int x = node.x();
        int y = node.y();
        if (x<0 || x>=n || y<0 || y>=m) return;
        if (!Node.isLand(x, y, grid))   return;
        
        for (Direction dir : new Direction[] {Direction.UP, Direction.DOWN, Direction.LEFT, Direction.RIGHT}) {
            Node neighbor = Node.valueOf(x+dir.x(), y+dir.y());
            if (visited.add(neighbor)) {
                dfs(neighbor, grid);
            }
        }
    }
}

enum Direction {
    UP      (-1, 0),
    DOWN    (1, 0),
    LEFT    (0, -1),
    RIGHT   (0, 1);
    
    private int x, y;
    Direction(int x, int y) {
        this.x = x;
        this.y = y;
    }
    
    public int x() {
        return this.x;
    }
    
    public int y() {
        return this.y;
    }
    
}

class Node {
    private final int x, y;
    private Node(int x, int y) {
        this.x = x;
        this.y = y;
    }
    
    public static Node valueOf(int x, int y) {
        return new Node(x, y);
    }
    
    public static boolean isLand(int x, int y, char[][] grid) {
        return grid[x][y]=='1';
    }
    
    public int x() {
        return this.x;
    }
    
    public int y() {
        return this.y;
    }
    
    @Override
    public boolean equals(Object o) {
        if (o == this)  return true;
        if (!(o instanceof Node))   return false;
        Node co = (Node) o;
        if (this.x==co.x && this.y==co.y) return true;
        return false;
    }
    
    @Override
    public int hashCode() {
        int ret = 17;
        ret += ret * 31 * this.x;
        ret += ret * 31 * this.y;
        return ret;
    }
}

imgRuntime: around 40ms