79. Word Search
2026/1/12大约 2 分钟约 550 字
79. Word Search
难度: Medium
题目描述
Given an m x n grid of characters board and a string word, return true if word exists in the grid.
The word can be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once.
Example 1:

Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED" Output: true
Example 2:

Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "SEE" Output: true
Example 3:

Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCB" Output: false
Constraints:
m == board.lengthn = board[i].length1 <= m, n <= 61 <= word.length <= 15boardandwordconsists of only lowercase and uppercase English letters.
Follow up: Could you use search pruning to make your solution faster with a larger board?
解题思路
代码实现
解决方案
java
class Solution {
public boolean exist(char[][] board, String word) {
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[0].length; j++) {
if (backStack(board, new boolean[board.length][board[0].length], word, 0, i, j)) {
return true;
}
}
}
return false;
}
private boolean backStack(char[][] board, boolean[][] record, String word, int index, int row, int col) {
if (index == word.length()) {
return true;
}
if (col < 0 || row < 0 || col >= board[0].length || row >= board.length) {
return false;
}
if (record[row][col]) {
return false;
}
char targetChar = word.charAt(index);
if (board[row][col] == targetChar) {
record[row][col] = true;
boolean a = backStack(board, record, word, index + 1, row, col + 1);
if (a) {
return true;
}
boolean b = backStack(board, record, word, index + 1, row, col - 1);
if (b) {
return true;
}
boolean c = backStack(board, record, word, index + 1, row + 1, col);
if (c) {
return true;
}
boolean d = backStack(board, record, word, index + 1, row - 1, col);
if (d) {
return true;
}
}
record[row][col] = false;
return false;
}
}