题目连接
Word Search
Description
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 =[
[‘A’,’B’,’C’,’E’], [‘S’,’F’,’C’,’S’], [‘A’,’D’,’E’,’E’] ] word = “ABCCED”, -> returns true, word = “SEE”, -> returns true, word = “ABCB”, -> returns false.const int dx[] = { 0, 0, -1, 1 }, dy[] = { -1, 1, 0, 0 };class Solution {public: int n, H, W; bool exist(vector>& board, string word) { n = word.length(); H = board.size(), W = board[0].size(); queue >q; for (int i = 0; i < H; i++) { for (int j = 0; j < W; j++) { if (word[0] == board[i][j]) { vector > vis(H, vector (W)); vis[i][j] = true; if (dfs(i, j, vis, board, word, 1)) return true; } } } return false; } bool dfs(int x, int y, vector >& vis, vector >& board, string word, int cur) { if (cur == n) return true; for (int i = 0; i < 4; i++) { int nx = x + dx[i], ny = y + dy[i]; if (nx < 0 || nx >= H || ny <0 || ny >= W) continue; if (board[nx][ny] == word[cur] && !vis[nx][ny]) { vis[nx][ny] = true; if (dfs(nx, ny, vis, board, word, cur + 1)) return true; vis[nx][ny] = false; } } return false; }};