Created
October 8, 2017 04:08
-
-
Save BiruLyu/807f3960d6ea16f933a7de5bd4058a06 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public int numDistinctIslands(int[][] grid) { | |
if (grid == null || grid.length < 1 || grid[0].length < 1) return 0; | |
int m = grid.length, n = grid[0].length; | |
Set<String> res = new HashSet<>(); | |
for (int i = 0; i < m; i++) { | |
for (int j = 0; j < n; j++) { | |
Set<String> set = new HashSet<>(); | |
if (grid[i][j] == 1) { | |
dfs(grid, i, j, i, j, set); | |
res.add(set.toString()); | |
} | |
} | |
} | |
return res.size(); | |
} | |
public void dfs(int[][] grid, int i, int j, int baseX, int baseY, Set<String> set) { | |
int m = grid.length, n = grid[0].length; | |
if (i < 0 || i >= m || j < 0 || j >= n || grid[i][j] == 0) return; | |
set.add((i - baseX) + "_" + (j - baseY)); | |
grid[i][j] = 0; | |
dfs(grid, i + 1, j, baseX, baseY, set); | |
dfs(grid, i - 1, j, baseX, baseY, set); | |
dfs(grid, i, j - 1, baseX, baseY, set); | |
dfs(grid, i, j + 1, baseX, baseY, set); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment