LeetCode 695. Max Area of Island javascript解決方案

pimkle發表於2017-12-14

題意:
尋找最大島。
leetcode.com/problems/ma…
傳入:
[[0,0,1,0,0,0,0,1,0,0,0,0,0],
 [0,0,0,0,0,0,0,1,1,1,0,0,0],
 [0,1,1,0,1,0,0,0,0,0,0,0,0],
 [0,1,0,0,1,1,0,0,1,0,1,0,0],
 [0,1,0,0,1,1,0,0,1,1,1,0,0],
 [0,0,0,0,0,0,0,0,0,0,1,0,0],
 [0,0,0,0,0,0,0,1,1,1,0,0,0],
 [0,0,0,0,0,0,0,1,1,0,0,0,0]]

傳出:
6


思路:
從左上角開始一個個往右下角數,每一個數出來連塊最大數,然後輸出。
連塊最大數計算:按照 上、右、下、左 方向,取得連著的值,推入暫存陣列,再對連著的值進行遞迴呼叫,再推入暫存陣列。

程式碼:

/**
* @param {number[][]} grid
* @return {number}
*/
var maxAreaOfIsland = function(grid) {
   function add(list, i , j){
       if(!list)
           return;
       for(var k = 0; k < list.length; ++k){
           if(list[k].i === i && list[k].j === j)
               return false;
       }
       list.push({i, j});
       return true;
   }
   function deepSearch(i, j, list){
       if(!list)
           list = [];
       if(grid[i][j]){
           add(list, i, j);
       }
       if(j > 0 && grid[i][j - 1]){
           if(add(list, i, j - 1)){
               deepSearch(i, j - 1, list);
           }
       }
       if(i < grid.length - 1 && grid[i + 1][j]){
           if(add(list, i + 1, j)){
               deepSearch(i + 1, j, list);
           }
       }
       if(grid.length && j < grid[0].length - 1 && grid[i][j + 1]){
           if(add(list, i, j + 1)){
               deepSearch(i, j + 1, list);
           }
       }
       if(i > 0 && grid[i - 1][j]){
           if(add(list, i - 1, j)){
               deepSearch(i - 1, j, list);
           }
       }
       return list.length;
   }
   function countArea(i, j){
       if(j > 0 && grid[i][j - 1]) // 不是最左上角的不count
           return 0;
       if(i > 0 && grid[i - 1][j])
           return 0;
       return deepSearch(i, j);
   }
   var max = 0;
   for(var i = 0;i < grid.length; ++i){
       for(var j = 0;j < grid[i].length; ++j){
           var obj = grid[i][j];
           if(obj){
               var tmp = countArea(i, j);
               max = tmp > max ? tmp : max;
           }
       }
   }
   return max;
};
複製程式碼

相關文章