๐ ๐ 130. ่ขซๅด็ป็ๅบๅ
2022ๅนด6ๆ20ๆฅ
- algorithm
๐ ๐ 130. ่ขซๅด็ป็ๅบๅ
้พๅบฆ: ๐ ๐
้ฎ้ขๆ่ฟฐ
่งฃๆณ
class Solution {
public void solve(char[][] board) {
// ๆ่ทฏ๏ผ
// ่ฆๆพๅฐๅชไบๆฏ่ขซ X ็ฏ็ป็ 0
// ๅณ๏ผๅชไบๆฏไธ่ขซ X ็ฏ็ป็ 0๏ผ ==> ไธ่พน็็ 0 ็ธ่ฟ็ 0 ๅฐฑๆฏไธ่ขซ็ฏ็ป็
// ๆพๅฐ่พน็็ 0 ๏ผไปฅ ่ฏฅ็นๅๅไธชๆนๅๅๆทฑๅบฆไผๅ
ๆ็ดข
int row = board.length;
int col = board[0].length;
for(int i = 0; i < row; i ++) {
if(board[i][0] == 'O') {
mySol(board, row, col, i, 0);
}
if(board[i][col - 1] == 'O') {
mySol(board, row, col, i, col - 1);
}
}
for(int j = 0; j < col; j ++) {
if(board[0][j] == 'O') {
mySol(board, row, col, 0, j);
}
if(board[row - 1][j] == 'O') {
mySol(board, row, col, row - 1, j);
}
}
// ๅฐ board[][] ไธญ็ '#' ่ฟๅไธบ 'O'
for(int i = 0; i < row; i ++) {
for(int j = 0; j < col; j ++) {
if(board[i][j] == '#') {
board[i][j] = 'O';
} else if(board[i][j] == 'O') {
board[i][j] = 'X';
}
}
}
}
private void mySol(char[][] board, int row, int col, int i, int j) {
// ้ๅฝ็ปๆญขๆกไปถ
if(!isValid(row, col, i, j)) {
return;
}
if(board[i][j] == 'X' || board[i][j] == '#') {
return;
}
// board[i][j]
board[i][j] = '#'; // [i, j] == O ่ฟ่กๆ ่ฎฐ๏ผ่ฏฅ็น่กจ็คบ O ๅฏไปฅๅฐ่พพ
mySol(board, row, col, i + 1, j);
mySol(board, row, col, i - 1, j);
mySol(board, row, col, i, j - 1);
mySol(board, row, col, i, j + 1);
}
private boolean isValid(int row, int col, int i, int j) {
if(i < 0 || j < 0) {
return false;
}
if(i >= row || j >= col) {
return false;
}
return true;
}
}