解答
java
class Solution {
public boolean exist(char[][] board, String word) {
int rowLength = board.length;
int colomnLength = board[0].length;
boolean[][] boardUsed = new boolean[rowLength][colomnLength];
for (int i = 0; i < rowLength; ++i) {
Arrays.fill(boardUsed[i], false);
}
char firstChar = word.charAt(0);
for (int row = 0; row < rowLength; ++row) {
for (int colomn = 0; colomn < colomnLength; ++colomn) {
if (board[row][colomn] == firstChar) {
for (int i = 0; i < rowLength; ++i) {
Arrays.fill(boardUsed[i], false);
}
boardUsed[row][colomn] = true;
if (exist(board, word, 1, boardUsed, row, colomn)) {
return true;
}
}
}
}
return false;
}
public boolean exist(char[][] board, String word, int index, boolean[][] boardUsed, int rowIndex, int colomnIndex) {
if (index >= word.length()) {
return true;
}
int rowLength = board.length;
int colomnLength = board[0].length;
int nextIndex = index + 1;
char c = word.charAt(index);
boardUsed[rowIndex][colomnIndex] = true;
int nextRow = 0;
int nextColomn = 0;
// 上一行
{
nextRow = rowIndex - 1;
nextColomn = colomnIndex;
if (nextRow >= 0 && !boardUsed[nextRow][nextColomn] && board[nextRow][nextColomn] == c) {
if (exist(board, word, nextIndex, boardUsed, nextRow, nextColomn)) {
return true;
} else {
boardUsed[nextRow][nextColomn] = false;
}
}
}
// 下一行
{
nextRow = rowIndex + 1;
nextColomn = colomnIndex;
if (nextRow < rowLength && !boardUsed[nextRow][nextColomn] && board[nextRow][nextColomn] == c) {
if (exist(board, word, nextIndex, boardUsed, nextRow, nextColomn)) {
return true;
} else {
boardUsed[nextRow][nextColomn] = false;
}
}
}
// 左边
{
nextRow = rowIndex;
nextColomn = colomnIndex - 1;
if (nextColomn >= 0 && !boardUsed[nextRow][nextColomn] && board[nextRow][nextColomn] == c) {
if (exist(board, word, nextIndex, boardUsed, nextRow, nextColomn)) {
return true;
} else {
boardUsed[nextRow][nextColomn] = false;
}
}
}
// 右边
{
nextRow = rowIndex;
nextColomn = colomnIndex + 1;
if (nextColomn < colomnLength && !boardUsed[nextRow][nextColomn] && board[nextRow][nextColomn] == c) {
if (exist(board, word, nextIndex, boardUsed, nextRow, nextColomn)) {
return true;
} else {
boardUsed[nextRow][nextColomn] = false;
}
}
}
return false;
}
}
总结
回溯法。