题目
五子棋棋盘,被围的'O‘全部变成’X‘
代码
public class Solution {
public void solve(char[][] board) {
if(board == null || board.length ==0){
return ;
}
int row = board.length;
int col = board[0].length;
boolean[][] visited = new boolean[row][col];
for(int j = 0;j<col;j++){
useme(board,0,j,visited);
useme(board,row-1,j,visited);
}
for(int i = 0;i<row;i++){
useme(board,i,0,visited);
useme(board,i,col-1,visited);
}
for(int i=0;i<row;i++){
for(int j=0;j<col;j++){
if(!visited[i][j] && board[i][j]=='O'){
board[i][j]='X';
}
}
}
}
public void useme(char[][] board,int i,int j,boolean[][] visited){
if(test(board,i,j) && !visited[i][j] && board[i][j]=='O'){
visited[i][j]=true;
useme(board,i-1,j,visited);
useme(board,i+1,j,visited);
useme(board,i,j-1,visited);
useme(board,i,j+1,visited);
}
}
public boolean test(char[][] board,int i ,int j){
int row = board.length;
int col = board[0].length;
if(i<0 || i>=row ||j<0|| j>=col){
return false;
}
return true;
}
}
这个代码会 StackOverflow,把bfs的部分用queue改写就好。