[lintcode] problem 860 – number of distinct islands

Given a non-empty 2D array grid of 0’s and 1’s, an island is a group of 1’s (representing land) connected 4-directionally (horizontal or vertical). You may assume all four edges of the grid are surrounded by water.

Count the number of distinct islands. An island is considered to be the same as another if and only if one island has the same shape as another island (and not rotated or reflected).

Notice that:

1
2
11
1

and

1
2
 1
11

are considered different island, because we do not consider reflection / rotation.

Note

The length of each dimension in the given grid does not exceed 50.

Example

No.1

Input:

1
2
3
4
5
6
[
[1,1,0,0,1],
[1,0,0,0,0],
[1,1,0,0,1],
[0,1,0,1,1]
]

Output: 3

Explanation:

1
2
3
4
11   1    1
1 11
11
1

No.2

Input:

1
2
3
4
5
6
[
[1,1,0,0,0],
[1,1,0,0,0],
[0,0,0,1,1],
[0,0,0,1,1]
]

Output: 1

Code

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
37
38
39
40
41
42
43
44
45
46
47
public int (int[][] grid) {
int n = grid.length;
int m = grid[0].length;
boolean[][] visit = new boolean[n][m];
Set<List<List<Integer>>> count = new HashSet<>();

for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (grid[i][j] == 1 && !visit[i][j]) {
List<List<Integer>> island = bfs(grid, visit, i, j);
count.add(island);
}
}
}

return count.size();
}

private List<List<Integer>> bfs(int[][] grid, boolean[][] visit, int i, int j) {
int n = grid.length;
int m = grid[0].length;
int[][] directions = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
List<List<Integer>> island = new ArrayList<>();
Queue<int[]> queue = new LinkedList<>();
queue.offer(new int[] {i, j});
visit[i][j] = true;

while (!queue.isEmpty()) {
int[] pos = queue.poll();
List<Integer> list = new ArrayList<>();
list.add(pos[0] - i);
list.add(pos[1] - j);
island.add(list);

for (int[] direction : directions) {
int x = pos[0] + direction[0];
int y = pos[1] + direction[1];

if (x >= 0 && x < n && y >= 0 && y < m && grid[x][y] == 1 && !visit[x][y]) {
queue.offer(new int[] {x, y});
visit[x][y] = true;
}
}
}

return island;
}