下面是我找到最大島嶼面積的代碼,但由于某種原因它一直未能通過這個測驗用例:[[1],[1]]
我不完全確定出了什么問題,我一直在想使用這種方法沒有任何可能的解決方案。它認為這段代碼不能正常作業的一個可能原因是在底部的 for 回圈中呼叫 dfs() 時 JS 的同步性質。
var maxAreaOfIsland = function(grid) {
let maxArea = 0
let currArea = 0
let dirs = [
[0,1],
[1,0],
[-1,0],
[0,-1]
]
function dfs(r,c){
if(grid[r][c] === 0) return
currArea
grid[r][c] = 0
for(let [row,col] of dirs){
let nr = r row
let nc = c col
if(nr<0 || nc< 0|| nr >= grid.length|| nc >= grid[0].length){
return
}
dfs(nr,nc)
}
}
for(let i = 0; i < grid.length; i ){
for(let j = 0; j< grid[0].length; j ){
if(grid[i][j] === 1){
currArea = 0
dfs(i,j)
if(currArea > maxArea){
maxArea = currArea
}
}
}
}
return maxArea
};
console.log(maxAreaOfIsland( [[1],[1]] ))
uj5u.com熱心網友回復:
看起來該dfs函式的意思是在非零位置周圍搜索,在currArea找到更多非零位置時遞增,并注意不要跑出矩陣的邊緣。將return在邊界檢查,但是,當它應該只是放棄搜索continue。一個更改,標有評論...
var maxAreaOfIsland = function(grid) {
let maxArea = 0
let currArea = 0
let dirs = [
[0,1],
[1,0],
[-1,0],
[0,-1]
]
function dfs(r,c){
if(grid[r][c] === 0) return
currArea
grid[r][c] = 0
for(let [row,col] of dirs){
let nr = r row
let nc = c col
if(nr<0 || nc< 0|| nr >= grid.length|| nc >= grid[0].length){
continue; // <-- notice, we keep searching
}
dfs(nr,nc)
}
}
for(let i = 0; i < grid.length; i ){
for(let j = 0; j< grid[0].length; j ){
if(grid[i][j] === 1){
currArea = 0
dfs(i,j)
if(currArea > maxArea){
maxArea = currArea
}
}
}
}
return maxArea
};
console.log(maxAreaOfIsland( [[1],[1]] ))
uj5u.com熱心網友回復:
試試這個:我猜你需要在繼續之前檢查單元格在網格中是否有效。
var maxAreaOfIsland = function(grid) {
let maxArea = 0
let currArea = 0
let dirs = [
[0,1],
[1,0],
[-1,0],
[0,-1]
]
function dfs(r,c){
if(r<0 || c< 0|| r >= grid.length|| c >= grid[0].length)
return
if(grid[r][c] === 0) return
currArea
grid[r][c] = 0
for(let [row,col] of dirs){
let nr = r row
let nc = c col
dfs(nr,nc)
}
}
for(let i = 0; i < grid.length; i ){
for(let j = 0; j< grid[0].length; j ){
if(grid[i][j] === 1){
currArea = 0
dfs(i,j)
if(currArea > maxArea){
maxArea = currArea
}
}
}
}
return maxArea
};
console.log(maxAreaOfIsland( [[1],[1]] ))
我建議使用 C ,因為與 JS 相比,相同的代碼將花費 8 倍的時間
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/395982.html
標籤:javascript 算法
上一篇:K步中可能的最大n位數
