Number of Distinct Islands
Description
null
Solution(javascript)
/**
* @param {number[][]} grid
* @return {number}
*/
const numDistinctIslands = function (grid) {
const visited = grid.map(x => x.map(() => false))
const dfs = (row, column, p) => {
if (row < 0 || row > grid.length - 1
|| column < 0 || column > grid[row].length - 1
) {
return p
}
if (visited[row][column]) {
return p
}
visited[row][column] = true
if (grid[row][column] === 0) {
return p
}
p = dfs(row + 1, column, `${p}d`)
p = dfs(row - 1, column, `${p}u`)
p = dfs(row, column - 1, `${p}l`)
p = dfs(row, column + 1, `${p}r`)
return p
}
const set = new Set()
for (let i = 0; i < grid.length; i++) {
for (let j = 0; j < grid[i].length; j++) {
if (grid[i][j] === 1 && !visited[i][j]) {
const path = dfs(i, j, 'o')
set.add(path)
}
}
}
return set.size
}