694 Number of Distinct Islands
1. 题目:
11000
11000
00011
0001111011
10000
00001
110112. 思路
3. Implementation
Last updated
11000
11000
00011
0001111011
10000
00001
11011Last updated
11
1 1
11class Solution {
public int numDistinctIslands(int[][] grid) {
if (grid == null || grid.length == 0) {
return 0;
}
int m = grid.length, n = grid[0].length;
int[][] directions = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
Set<List<List<Integer>>> set = new HashSet<>();
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (grid[i][j] == 1) {
List<List<Integer>> hashKey = new ArrayList<>();
searchByBFS(i, j, directions, grid, hashKey);
set.add(hashKey);
}
}
}
return set.size();
}
public void searchByBFS(int row, int col, int[][] directions, int[][] grid, List<List<Integer>> hashKey) {
grid[row][col] = 0;
Queue<Integer> queue = new LinkedList<>();
int n = grid[0].length;
queue.add(row * n + col);
while (!queue.isEmpty()) {
int curPoint = queue.remove();
int curRow = curPoint / n;
int curCol = curPoint % n;
for (int i = 0; i < 4; i++) {
int nextRow = curRow + directions[i][0];
int nextCol = curCol + directions[i][1];
if (isValid(nextRow, nextCol, grid)) {
grid[nextRow][nextCol] = 0;
hashKey.add(Arrays.asList(nextRow - row, nextCol - col));
queue.add(nextRow * n + nextCol);
}
}
}
}
public boolean isValid(int row, int col, int[][] grid) {
return row >= 0 && row < grid.length && col >= 0 && col < grid[0].length && grid[row][col] == 1;
}
}