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.
For example,
Given board =
1 2 3 4 5 |
[ ['A','B','C','E'], ['S','F','C','S'], ['A','D','E','E'] ] |
word = "ABCCED"
, -> returns true
,
word = "SEE"
, -> returns true
,
word = "ABCB"
, -> returns false
.
Idea:
Search, depth first search
Solution:
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
class Solution { public: bool exist(vector<vector<char>> &board, string word) { if(board.size()==0) return false; h = board.size(); w = board[0].size(); for(int i=0;i<w;i++) for(int j=0;j<h;j++) if(search(board, word, 0, i, j)) return true; return false; } bool search(vector<vector<char>> &board, const string& word, int d, int x, int y) { if(x<0 || x==w || y<0 || y==h || word[d] != board[y][x]) return false; // Found the last char of the word if(d==word.length()-1) return true; char cur = board[y][x]; board[y][x] = 0; bool found = search(board, word, d+1, x+1, y) || search(board, word, d+1, x-1, y) || search(board, word, d+1, x, y+1) || search(board, word, d+1, x, y-1); board[y][x] = cur; return found; } private: int w; int h; }; |
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
# Author: Huahua, running time: 216 ms class Solution: def exist(self, board: List[List[str]], word: str) -> bool: if not board: return False h, w = len(board), len(board[0]) def search(d: int, x: int, y: int) -> bool: if x < 0 or x == w or y < 0 or y == h or word[d] != board[y][x]: return False if d == len(word) - 1: return True cur = board[y][x] board[y][x] = '' found = search(d + 1, x + 1, y) or search(d + 1, x - 1, y) or search(d + 1, x, y + 1) or search(d + 1, x, y - 1) board[y][x] = cur return found return any(search(0, j, i) for i in range(h) for j in range(w)) |