我有一个2D数组的副本,它返回的阅读属性是undefined,但原始数组没有。有人知道这是为什么吗?我附上了我的代码。我想这可能与我复制数组的方式有关,但当我console.log它们时,它们返回的是相同的东西,只是一个填充了false,另一个填充了字符串数字。
/**
* @param {character[][]} grid
* @return {number}
*/
var numIslands = function(grid) {
let MAX_X = grid.length;
let MAX_Y = grid[0].length;
let num_of_islands = 0;
const visited = grid.map((row) => {
return (
row.map((square) => {
return (
false
)
})
)
})
console.log(grid);
console.log(visited);
for(let x = 0; x < MAX_X; x++) {
for(let y = 0; y < MAX_Y; y++) {
if(grid[x][y] === '1' && !visited[x][y]) {
num_of_islands+= 1;
DFS(grid, x, y, visited)
}
}
}
return num_of_islands
};
function DFS(grid, x, y, visited) {
if(x < 0 || x >= grid.length || y < 0 || y >= grid[0].length) {
return;
}
if(grid[x][y] === '0' || visited[x][y]) {
return;
}
grid[x][y] = '0';
visited[x][y] = true;
DFS(grid, x + 1, y);
DFS(grid, x - 1, y);
DFS(grid, x, y + 1);
DFS(grid, x, y - 1);
}
let grid = [["1","1","1","1","0"],["1","1","0","1","0"],["1","1","0","0","0"],["0","0","0","0","0"]];
console.log(numIslands(grid));
1条答案
按热度按时间uemypmqf1#
出现的错误"reading property of undefined"与复制数组的方式无关,而是与未提供参数的函数参数有关。
递归调用只传递3个参数,而实际上应该传递4个。因此,请更改以下内容:
签署人: