Advertisement
1988coder

694. Number of Distinct Islands

Jan 1st, 2019
124
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.84 KB | None | 0 0
  1. /**
  2.  * DFS Recursive. This solution create a path signature of each island and save
  3.  * it in a HashSet. HashSet keeps one copy of each distinct signature.
  4.  *
  5.  * Time Complexity: O(M * N) - All cells in the grids ar visited twice.
  6.  *
  7.  * Space Complexity: O(M * N) - This is for recursion stack and visited boolean
  8.  * array
  9.  *
  10.  * M = Number of rows in the grid. N = Number of columns in the grid.
  11.  */
  12. class Solution {
  13.     public int numDistinctIslands(int[][] grid) {
  14.         if (grid == null || grid.length == 0 || grid[0].length == 0) {
  15.             return 0;
  16.         }
  17.         if (grid.length == 1 && grid[0].length == 1) {
  18.             if (grid[0][0] == 1) {
  19.                 return 1;
  20.             } else {
  21.                 return 0;
  22.             }
  23.         }
  24.  
  25.         boolean[][] visited = new boolean[grid.length][grid[0].length];
  26.         Set<String> set = new HashSet();
  27.  
  28.         for (int i = 0; i < grid.length; i++) {
  29.             for (int j = 0; j < grid[0].length; j++) {
  30.                 if (grid[i][j] == 1 && !visited[i][j]) {
  31.                     StringBuilder path = new StringBuilder();
  32.                     dfsHelper(grid, i, j, visited, path, "o");
  33.                     set.add(path.toString());
  34.                 }
  35.             }
  36.         }
  37.  
  38.         return set.size();
  39.     }
  40.  
  41.     private void dfsHelper(int[][] grid, int i, int j, boolean[][] visited, StringBuilder path, String dir) {
  42.         if (i < 0 || j < 0 || i >= grid.length || j >= grid[0].length || grid[i][j] != 1 || visited[i][j]) {
  43.             return;
  44.         }
  45.         visited[i][j] = true;
  46.         path.append(dir);
  47.         dfsHelper(grid, i + 1, j, visited, path, "d");
  48.         dfsHelper(grid, i - 1, j, visited, path, "u");
  49.         dfsHelper(grid, i, j + 1, visited, path, "r");
  50.         dfsHelper(grid, i, j - 1, visited, path, "l");
  51.         path.append("b");
  52.     }
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement