题意:
寻找最大岛。
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]) // 不是最左上角的不countreturn 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;
};
复制代码