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 X
感染列岛 哈哈
挺有意思一道题,讲解 和code http://www.cnblogs.com/huntfor/p/3898068.html
题解
// XXXXX --> X X X X X --> XXXX
// XOXOX X# X O X XOXX
// XOXOX X# X O X XOXX
// XOXXX X# X X X XOXX
用queue来存储,这样后面加进来的传染源就不会干扰之前的传染源传染
public class Solution { public void solve(char[][] board) { if(board==null||board.length<=1||board[0].length<=1 ) return; for(int i=0;i<board.length;i++){ // fist col helper(board, i, 0); helper(board, i, board[0].length-1); // last col } for(int j=0;j<board[0].length;j++){ //first row helper(board, 0, j); helper(board, board.length-1, j); // last row } for(int i=0;i<board.length;i++){ for(int j=0;j<board[0].length;j++){ if(board[i][j]!=‘#‘){ board[i][j] = ‘X‘; }else board[i][j] = ‘O‘; } } } private void helper(char[][] b, int i, int j){ if(b[i][j]!=‘O‘) return; b[i][j]=‘#‘; int code = b[0].length*i+j; LinkedList<Integer> queue = new LinkedList<Integer>(); // 为了从外围逐渐向中心渲染 queue.add(code); while(!queue.isEmpty()){ int c = queue.poll(); int row = c/b[0].length; int col = c%b[0].length; //up if(row>0 && b[row-1][col]==‘O‘){ b[row-1][col]=‘#‘; queue.add(b[0].length*(row-1)+col); } //down if(row<b.length-1 && b[row+1][col]==‘O‘){ b[row+1][col]=‘#‘; queue.add(b[0].length*(row+1)+col); } //left if(col>0 && b[row][col-1]==‘O‘){ b[row][col-1]=‘#‘; queue.add(b[0].length*(row)+col-1); } //right if(col< b[0].length-1 && b[row][col+1]==‘O‘){ b[row][col+1]=‘#‘; queue.add(b[0].length*(row)+col+1); } } } }
时间: 2024-10-09 08:44:19