首页>itarticle>[lintcode] problem 860 – number of distinct islands
[lintcode] problem 860 – number of distinct islands
admin11月 13, 20200
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.
publicint(int[][] grid){ int n = grid.length; int m = grid[0].length; boolean[][] visit = newboolean[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(newint[] {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(newint[] {x, y}); visit[x][y] = true; } } }
近期评论