1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| class Solution { private int m, n; public int numDistinctIslands(int[][] grid) { Set<String> set = new HashSet<>(); if (grid == null || grid[0].length == 0) return 0; 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) { StringBuilder sb = new StringBuilder(); dfs(grid, i, j, sb, "o"); set.add(sb.toString()); } } } return set.size(); } public void dfs(int[][] grid, int i, int j, StringBuilder sb, String dir) { if (i < 0 || j < 0 || i >= m || j >= n || grid[i][j] == 0) return; sb.append(dir); grid[i][j] = 0; dfs(grid, i+1, j, sb, "r"); dfs(grid, i-1, j, sb, "l"); dfs(grid, i, j+1, sb, "u"); dfs(grid, i, j-1, sb, "d"); sb.append("b"); } }
|