|
| 1 | +/** |
| 2 | +
|
| 3 | +Given a non-empty 2D array grid of 0's and 1's, |
| 4 | +an island is a group of 1's (representing land) connected 4-directionally (horizontal or vertical.) |
| 5 | +You may assume all four edges of the grid are surrounded by water. |
| 6 | +
|
| 7 | +Count the number of distinct islands. An island is considered to |
| 8 | +be the same as another if and only if one island can |
| 9 | +be translated (and not rotated or reflected) to equal the other. |
| 10 | +
|
| 11 | +Example 1: |
| 12 | +11000 |
| 13 | +11000 |
| 14 | +00011 |
| 15 | +00011 |
| 16 | +
|
| 17 | +Given the above grid map, return 1. |
| 18 | +
|
| 19 | +Example 2: |
| 20 | +11011 |
| 21 | +10000 |
| 22 | +00001 |
| 23 | +11011 |
| 24 | +
|
| 25 | +Given the above grid map, return 3. |
| 26 | +
|
| 27 | +Notice that: |
| 28 | +11 |
| 29 | +1 |
| 30 | +and |
| 31 | + 1 |
| 32 | +11 |
| 33 | +are considered different island shapes, because we do not consider reflection / rotation. |
| 34 | +Note: The length of each dimension in the given grid does not exceed 50. |
| 35 | +
|
| 36 | +*/ |
| 37 | + |
| 38 | +/** |
| 39 | + * @param {number[][]} grid |
| 40 | + * @return {number} |
| 41 | + */ |
| 42 | +const numDistinctIslands = function(grid) { |
| 43 | + if (!grid.length) return 0; |
| 44 | + const pattern = new Set(); |
| 45 | + grid.forEach((rows, row) => { |
| 46 | + rows.forEach((val, col) => { |
| 47 | + if (val === 1) pattern.add(depthFirst(grid, row, col, "o")); |
| 48 | + }); |
| 49 | + }); |
| 50 | + return pattern.size; |
| 51 | +}; |
| 52 | + |
| 53 | +function depthFirst(graph, row, col, di) { |
| 54 | + if (graph[row] && graph[row][col]) { |
| 55 | + graph[row][col] = 0; |
| 56 | + let p = |
| 57 | + di + |
| 58 | + depthFirst(graph, row + 1, col, "d") + |
| 59 | + depthFirst(graph, row - 1, col, "u") + |
| 60 | + depthFirst(graph, row, col + 1, "r") + |
| 61 | + depthFirst(graph, row, col - 1, "l") + |
| 62 | + "b"; |
| 63 | + return p; |
| 64 | + } else return ""; |
| 65 | +} |
0 commit comments