[LeetCode][JavaScript]Surrounded Regions
Surrounded Regions
Given a 2D board containing 'X'
and 'O'
, capture all regions surrounded by 'X'
.
A region is captured by flipping all 'O'
s into 'X'
s in that surrounded region.
For example,
X X X X X O O X X X O X X O X X
After running your function, the board should be:
X X X X X X X X X X X X X O X Xhttps://leetcode.com/problems/surrounded-regions/
想通了其实很简单,但我就是折腾了好久...
第一轮找外围所有的O,这些点最后肯定不会被替换成X。
然后进行dfs,与这些点相连的点同样不会是X。
把这些不可能是X的点都标记成S,最后把所有O替换成X,把所有S替换成O。
我一开始尝试正着做,先缓存下需要标记的点,一口气都标成X,妥妥的MLE。
第二次尝试用bfs,先标记成X,如果不行回溯回去改成O,递归太深堆栈爆了...真是拙计
1 /** 2 * @param {character[][]} board 3 * @return {void} Do not return anything, modify board in-place instead. 4 */ 5 var solve = function(board) { 6 var m = board.length, n, i, j, queue = []; 7 for(i = 0; i < m; i++){ 8 n = board[0].length; 9 for(j = 0; j < n; j++){ 10 if(board[i][j] === 'O' && (i === 0 || i === m - 1 || j === 0 || j === n - 1)){ 11 queue.push({row : i, col : j}); 12 } 13 } 14 } 15 bfs(queue); 16 for(i = 0; i < m; i ++){ 17 for(j = 0; j < n; j ++){ 18 if(board[i][j] === 'O'){ 19 board[i][j] = 'X'; 20 }else if(board[i][j] === 'S'){ 21 board[i][j] = 'O'; 22 } 23 } 24 } 25 26 function bfs(queue){ 27 var i, j; 28 while(queue.length > 0){ 29 var top = queue.pop(); 30 i = top.row, j = top.col; 31 if(board[i][j] === 'S'){ 32 continue; 33 } 34 board[i][j] = 'S'; 35 if(board[i + 1] && board[i + 1][j] && board[i + 1][j] === 'O'){ 36 queue.push({row : i + 1, col : j}); 37 } 38 if(board[i - 1] && board[i - 1][j] && board[i - 1][j] === 'O'){ 39 queue.push({row : i - 1, col : j}); 40 } 41 if(board[i][j + 1] && board[i][j + 1] === 'O'){ 42 queue.push({row : i, col : j + 1}); 43 } 44 if(board[i][j - 1] && board[i][j - 1] === 'O'){ 45 queue.push({row : i, col : j - 1}); 46 } 47 } 48 } 49 };
TLE:
1 /** 2 * @param {character[][]} board 3 * @return {void} Do not return anything, modify board in-place instead. 4 */ 5 var solveTLE = function(board) { 6 var m = board.length, n, i, j; 7 for(i = 0; i < m; i++){ 8 n = board[0].length; 9 for(j = 0; j < n; j++){ 10 if(board[i][j] === 'O'){ 11 bfs([{row : i, col : j}]); 12 } 13 } 14 } 15 for(i = 0; i < m; i++){ 16 for(j = 0; j < n; j++){ 17 if(board[i][j] === 'A'){ 18 board[i][j] = 'X'; 19 } 20 } 21 } 22 23 function bfs(queue){ 24 var len = queue.length, top, i, j, res; 25 while(len--){ 26 top = queue.pop(); 27 i = top.row; j = top.col; 28 if(!board[i] || !board[i][j]){ 29 return false; 30 } 31 if(board[i][j] === 'O'){ 32 queue.push({row : i + 1, col : j}); 33 queue.push({row : i - 1, col : j}); 34 queue.push({row : i, col : j + 1}); 35 queue.push({row : i, col : j - 1}); 36 } 37 } 38 if(queue.length !== 0){ 39 board[i][j] = 'A'; 40 res = bfs(queue); 41 if(!res){ 42 board[i][j] = 'O'; 43 return false; 44 } 45 } 46 return true; 47 } 48 };
MLE写得太丑不贴了...