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 31 32 33 34 35 36
| class Solution { private final int[][] DIRECTIONS = new int[][] { { -1, 0 }, { 1, 0 }, { 0, -1 }, { 0, 1 } };
public int numDistinctIslands(int[][] grid) { int m = grid.length, n = grid[0].length; Set<String> paths = new HashSet<>(); for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (grid[i][j] == 1) { StringBuilder sb = new StringBuilder(); getPath(grid, i, j, sb); paths.add(sb.toString()); } } } return paths.size();
}
private void getPath(int[][] grid, int row, int col, StringBuilder sb) { grid[row][col] = 0; for (int i = 0; i < DIRECTIONS.length; i++) { int newRow = row + DIRECTIONS[i][0]; int newCol = col + DIRECTIONS[i][1]; if (!isOutOfBound(grid.length, grid[0].length, newRow, newCol) && grid[newRow][newCol] == 1) { sb.append(i); getPath(grid, newRow, newCol, sb); } } sb.append('0'); }
private boolean isOutOfBound(int m, int n, int row, int col) { return row < 0 || row >= m || col < 0 || col >= n; } }
|