Java DFS


  • 0
    class Solution {
        private int[][] dirs = {{0,1},{1,0},{0,-1},{-1,0}};
        private int m, n;
        private Set<String> set = new HashSet<>();
        private String code = "";
        public int numDistinctIslands(int[][] grid) {
            m = grid.length;
            n = grid[0].length;
            for (int i = 0; i < m; i++) {
                for (int j = 0; j < n; j++) {
                    if (grid[i][j] == 1) {
                        code = "";
                        helper(grid, i, j);
                        set.add(code);
                        System.out.println(i + ", " + j + ", " + code);
                    }
                }
            }
            return set.size();
        }
        private void helper(int[][] grid, int x, int y) {
            grid[x][y] = 0;
            for (int i = 0; i < 4; i++) {
                int nx = x + dirs[i][0], ny = y + dirs[i][1];
                if (nx < 0 || nx >= m || ny < 0 || ny >= n || grid[nx][ny] == 0) continue;
                code += i;
                helper(grid, nx, ny);
                code += ","; 
            }
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.