首页>itarticle>[lintcode] problem 804 – number of distinct islands ii
[lintcode] problem 804 – number of distinct islands ii
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 they have the same shape, or have the same shape after rotation (90, 180, or 270 degrees only) or reflection (left/right direction or up/down direction).
Note
The length of each dimension in the given grid does not exceed 50.
are considered same island shapes. Because if we make a 180 degrees clockwise rotation on the first island, then two islands will have the same shapes.
publicintnumDistinctIslands2(int[][] grid){ int m = grid.length; int n = grid[0].length; Set<String> set = new HashSet<>(); boolean[][] visit = newboolean[m][n];
for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (grid[i][j] == 1 && !visit[i][j]) { List<int[]> island = new ArrayList<>(); dfs(island, grid, visit, m, n, i, j); set.add(normalize(island)); } } }
return set.size(); }
privatevoiddfs(List<int[]> island, int[][] grid, boolean[][] visit, int m, int n, int x, int y){ island.add(newint[] {x, y}); visit[x][y] = true;
for (int[] dir : dirs) { int newX = x + dir[0]; int newY = y + dir[1];
if (newX < 0 || newY < 0 || newX >= m || newY >= n || grid[newX][newY] == 0 || visit[newX][newY]) continue;
dfs(island, grid, visit, m, n, newX, newY); } }
private String normalize(List<int[]> island){ List<int[]>[] shapes = new ArrayList[8]; String[] results = new String[8];
for (int i = 0; i < trans.length; i++) { int[] tran = trans[i]; shapes[i] = new ArrayList<>(); shapes[i + 4] = new ArrayList<>();
for (int i = 0; i < shapes.length; i++) { StringBuilder sb = new StringBuilder(); int originX = shapes[i].get(0)[0]; int originY = shapes[i].get(0)[1];
for (int[] point : shapes[i]) sb.append(point[0] - originX).append(",").append(point[1] - originY).append(",");
近期评论