๐ 79. ๅ่ฏๆ็ดข
2022ๅนด10ๆ10ๆฅ
- algorithm
๐ 79. ๅ่ฏๆ็ดข
้พๅบฆ: ๐
้ฎ้ขๆ่ฟฐ
่งฃๆณ
class Solution {
public boolean exist(char[][] board, String word) {
// ๆ่ทฏ๏ผ
// ๅๆบฏ
int row = board.length;
int col = board[0].length;
int len = word.length();
for(int i = 0; i < row; i ++) {
for(int j = 0; j < col; j ++) {
if(board[i][j] == word.charAt(0)) {
if(mySol(board, word, row, col, len, 0, i, j)) {
return true;
}
}
}
}
return false;
}
private boolean mySol(char[][] board, String word, int row, int col, int len, int index, int i, int j) {
// ้ๅฝ็ปๆญขๆกไปถ
if(i < 0 || i >= row || j < 0 || j >= col) {
return false;
}
if(word.charAt(index) != board[i][j]) {
return false;
}
if(index == len - 1) {
return true;
}
// index < len - 1
char cur = board[i][j];
board[i][j] = '#'; // ๅๆ ่ฎฐๅป้
boolean res = mySol(board, word, row, col, len, index + 1, i - 1, j)
|| mySol(board, word, row, col, len, index + 1, i + 1, j)
|| mySol(board, word, row, col, len, index + 1, i, j - 1)
|| mySol(board, word, row, col, len, index + 1, i, j + 1);
if(res == true) {
return res;
} else {
board[i][j] = cur; // ่ฟๅ
return res;
}
}
}