给定一个二维的矩阵,包含 'X' 和 'O'(字母 O), 找到所有被 'X' 围绕的区域。
并将区域里所有 'O'用 'X' 填充。
例如,
X X X X
X O O X
X X O X
X O X X
运行你的函数后,该区域应该是:
X X X X
X X X X
X X X X
X O X X
详见:https://leetcode.com/problems/surrounded-regions/description/
Java实现:
class Solution { public void solve(char[][] board) { if(board==null){ return; } for(int i=0;i<board.length;++i){ for(int j=0;j<board[i].length;++j){ if((i==0||i==board.length-1||j==0||j==board[i].length-1)&&board[i][j]=='O'){ helper(board,i,j); } } } for(int i=0;i<board.length;++i){ for(int j=0;j<board[i].length;++j){ if(board[i][j]=='O'){ board[i][j]='X'; } if(board[i][j]=='$'){ board[i][j]='O'; } } } } private void helper(char[][] board,int i,int j){ if(board[i][j]=='O'){ board[i][j]='$'; if(i>0&&board[i-1][j]=='O'){ helper(board,i-1,j); } if(j<board[i].length-1&&board[i][j+1]=='O'){ helper(board,i,j+1); } if(i<board.length-1&&board[i+1][j]=='O'){ helper(board,i+1,j); } if(j>0&&board[i][j-1]=='O'){ helper(board,i,j-1); } } } }
参考:https://www.cnblogs.com/grandyang/p/4555831.html