原题链接:https://leetcode.com/problems/word-search/description/
做完上一题:212. Word Search II,我就知道有二必有一,那么再做这第一道题目就太简单了,不废话思路是一样的还是回溯法:
class Solution {
public boolean exist(char[][] board, String word) {
char[] wordChars = word.toCharArray();
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[0].length; j++) {
if (dfs(board, i, j, wordChars, 0)) {
return true;
}
}
}
return false;
}
public boolean dfs(char[][] board, int i, int j, char[] wordChars, int k) {
char c = board[i][j];
if (c == ‘#‘ || wordChars[k] != c) {
return false;
}
k++;
if (k == wordChars.length) {
return true;
}
board[i][j] = ‘#‘;
if (i > 0) {
if (dfs(board, i - 1, j, wordChars, k)) {
return true;
}
}
if (j > 0) {
if (dfs(board, i, j - 1, wordChars, k)) {
return true;
}
}
if (i < board.length - 1) {
if (dfs(board, i + 1, j, wordChars, k)) {
return true;
}
}
if (j < board[0].length - 1) {
if (dfs(board, i, j + 1, wordChars, k)) {
return true;
}
}
board[i][j] = c;
return false;
}
}