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.length
n = board[i].length
1 <= m, n <= 6
1 <= word.length <= 15
board
andword
consists of only lowercase and uppercase English letters.
Follow up: Could you use search pruning to make your solution faster with a larger board
?
Companies:
Amazon, Microsoft, Snapchat, Bloomberg, Twitter, Facebook, Apple, Goldman Sachs, Cisco, Google, Adobe, VMware, Cruise Automation, ByteDance, Bolt
Related Topics:
Array, Backtracking, Matrix
Similar Questions:
// OJ: https://leetcode.com/problems/word-search/
// Author: github.com/lzl124631x
// Time: O(MN * 4^K)
// Space: O(K)
class Solution {
public:
bool exist(vector<vector<char>>& A, string s) {
int M = A.size(), N = A[0].size(), dirs[4][2] = {{0,1},{0,-1},{1,0},{-1,0}};
function<bool(int, int, int)> dfs = [&](int x, int y, int i) {
if (x < 0 || x >= M || y < 0 || y >= N || A[x][y] != s[i]) return false;
if (i + 1 == s.size()) return true;
char c = A[x][y];
A[x][y] = 0;
for (auto &[dx, dy] : dirs) {
if (dfs(x + dx, y + dy, i + 1)) return true;
}
A[x][y] = c;
return false;
};
for (int i = 0; i < M; ++i) {
for (int j = 0; j < N; ++j) {
if (dfs(i, j, 0)) return true;
}
}
return false;
}
};