Given a 2D board and a word, find if the word exists in the grid.
The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.
Example:
board =
[
['A','B','C','E'],
['S','F','C','S'],
['A','D','E','E']
]
Given word = "ABCCED", return true.
Given word = "SEE", return true.
Given word = "ABCB", return false.
public class LC79WordSearch {
public boolean exist(char[][] board, String word) {
if (board == null || board.length == 0 || board[0].length == 0
|| word == null || word.length() == 0) return true;
int rows = board.length;
int cols = board[0].length;
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) {
// scan board, start with word first character
if (board[r][c] == word.charAt(0)) {
if (helper(board, word, r, c, 0)) {
return true;
}
}
}
}
return false;
}
private boolean helper(char[][] board, String word, int r, int c, int start) {
// already match word all characters, return true
if (start == word.length()) return true;
if (!isValid(board, r, c) ||
board[r][c] != word.charAt(start)) return false;
// mark visited
board[r][c] = '*';
boolean res = helper(board, word, r + 1, c, start + 1)
|| helper(board, word, r, c + 1, start + 1)
|| helper(board, word, r - 1, c, start + 1)
|| helper(board, word, r, c - 1, start + 1);
// backtracking to start position
board[r][c] = word.charAt(start);
return res;
}
private boolean isValid(char[][] board, int r, int c) {
return r >= 0 && r < board.length && c >= 0 && c < board[0].length;
}
}
Python3 Code
class Solution:
def exist(self, board: List[List[str]], word: str) -> bool:
m = len(board)
n = len(board[0])
def dfs(board, r, c, word, index):
if index == len(word):
return True
if r < 0 or r >= m or c < 0 or c >= n or board[r][c] != word[index]:
return False
board[r][c] = '*'
res = dfs(board, r - 1, c, word, index + 1) or dfs(board, r + 1, c, word, index + 1) or dfs(board, r, c - 1, word, index + 1) or dfs(board, r, c + 1, word, index + 1)
board[r][c] = word[index]
return res
for r in range(m):
for c in range(n):
if board[r][c] == word[0]:
if dfs(board, r, c, word, 0):
return True
/*
* @lc app=leetcode id=79 lang=javascript
*
* [79] Word Search
*/
function DFS(board, row, col, rows, cols, word, cur) {
// 边界检查
if (row >= rows || row < 0) return false;
if (col >= cols || col < 0) return false;
const item = board[row][col];
if (item !== word[cur]) return false;
if (cur + 1 === word.length) return true;
// 如果你用hashmap记录访问的字母, 那么你需要每次backtrack的时候手动清除hashmap,并且需要额外的空间
// 这里我们使用一个little trick
board[row][col] = null;
// 上下左右
const res =
DFS(board, row + 1, col, rows, cols, word, cur + 1) ||
DFS(board, row - 1, col, rows, cols, word, cur + 1) ||
DFS(board, row, col - 1, rows, cols, word, cur + 1) ||
DFS(board, row, col + 1, rows, cols, word, cur + 1);
board[row][col] = item;
return res;
}
/**
* @param {character[][]} board
* @param {string} word
* @return {boolean}
*/
var exist = function(board, word) {
if (word.length === 0) return true;
if (board.length === 0) return false;
const rows = board.length;
const cols = board[0].length;
for (let i = 0; i < rows; i++) {
for (let j = 0; j < cols; j++) {
const hit = DFS(board, i, j, rows, cols, word, 0);
if (hit) return true;
}
}
return false;
};