# LWC 53：694. Number of Distinct Islands

## LWC 53：694. Number of Distinct Islands

Problem:

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 can be translated (and not rotated or reflected) to equal the other.

Example 1:

11000 11000 00011 00011 Given the above grid map, return 1.

Example 2:

11011 10000 00001 11011 Given the above grid map, return 3. Notice that: 1 1 1 and 1 1 1 are considered different island shapes, because we do not consider reflection / rotation.

Note:

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

```0 1 0 0 0 1 0
1 1 1 0 1 1 1
0 1 0 0 0 1 0

```    int[][] dir = {{1, 0},{0, 1},{-1, 0},{0, -1}};
int[][] dp = new int[50 * 50 + 16][5]; // four direction

boolean[][] vis = new boolean[52][52];
int n, m;

Set<Integer> set = new HashSet<>();
public int numDistinctIslands(int[][] grid) {
n = grid.length;
if (n == 0) return 0;
m = grid[0].length;
if (m == 0) return 0;
vis = new boolean[52][52];
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
if (grid[i][j] == 1) {
if (!vis[i][j]) {
si = i;
sj = j;
dfs(grid, i, j);
}
}
}
}

return set.size();
}

boolean check(int i, int j) {
return i >= 0 && i < n && j >= 0 && j < m;
}

int si, sj;
public int[] dfs(int[][] grid, int x, int y) {
vis[x][y] = true;

for (int k = 0; k < 4; ++k) {
int[] d = dir[k];
int nx = d[0] + x;
int ny = d[1] + y;
if (check(nx, ny) && !vis[nx][ny] && grid[nx][ny] == 1) {
dp[x * m + y][k] = 1 + dfs(grid, nx, ny)[k];
dp[x * m + y][4] += (dp[nx * m + ny][4] + 1) * (k + 1);
}
}

for (int k = 0; k < 4; ++k) {
dp[x * m + y][4] += (((x - si + 1) * m + (y - sj + 1)) * 177) *  (dp[x * m + y][k] + 1) * (k + 1);
}

return dp[x * m + y];
}```

```    int[][] dir = {{1, 0},{0, 1},{-1, 0},{0, -1}};
char[]  c   = {'D','R','U','L'};
int n, m;

boolean[][] vis;

public int numDistinctIslands(int[][] grid) {
n = grid.length;
if (n == 0) return 0;
m = grid[0].length;
if (m == 0) return 0;
vis = new boolean[n][m];
Set<String> set = new HashSet<>();
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
if (grid[i][j] == 1 && !vis[i][j]) {
si = i;
sj = j;
}
}
}
return set.size();
}

int si, sj;
public String dfs(int[][] grid, int i, int j) {
String ans = "" + ((i - si) * m + (j - sj));
vis[i][j] = true;
for (int k = 0; k < 4; ++k) {
int[] d = dir[k];
int ni = d[0] + i;
int nj = d[1] + j;
if (check(ni, nj) && !vis[ni][nj] && grid[ni][nj] == 1) {
ans += c[k] + dfs(grid, ni, nj);
}
}
return ans;
}

boolean check(int i, int j) {
return i >= 0 && i < n && j >= 0 && j < m;
}```

0 条评论

## 相关文章

3816

721

1857

3287

2644

5735

2785

### [LeetCode]Math主题系列{第7，9，13，273题}

1.内容介绍 本篇文章记录在leetcode中Math主题下面的题目和自己的思考以及优化过程，具体内容层次按照{题目，分析，初解，初解结果，优化解，优化解结果，...

3407

701

2165