题目 |
题目传送门:传送门(点击此处)
题解 |
今天是六一儿童节,LeetCode也推出了分糖果的题目,真的是有心了,我也决定六月要好好打卡算法题了
思路
这道题的思路很容易想到,图的深度遍历,虽然是个中等难度的题目吧,不过也不难
- 遍历二维数组, 从每个节点都去判断是否能满足这个字符串
- 在判断每个元素是否能满足要求时,每遍历一个元素之后,将这个元素置为0,当遍历完一轮之后再恢复回去就可以了
- 其实到这就可以出代码了,题目不难
code
class Solution {
int rows, cols, idx;
char[][] board;
String word;
public boolean exist(char[][] board, String word) {
this.rows = board.length;
this.cols = board[0].length;
idx = 0;
this.board = board;
this.word = word;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (helper(i, j)) {
return true;
}
}
}
return false;
}
boolean helper(int i, int j) {
if (idx >= word.length()) {
return true;
}
if (i >= rows || i < 0 || j >= cols || j < 0 || board[i][j] == 0) {
return false;
}
boolean res = false;
if (board[i][j] == word.charAt(idx)) {
char c = board[i][j];
board[i][j] = 0;
idx++;
res = helper(i - 1, j) ||
helper(i, j - 1) ||
helper(i + 1, j) ||
helper(i, j + 1);
idx--;
board[i][j] = c;
}
return res;
}
}