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
.
Subscribe to see which companies asked this question
样板题
跟剑指offer:矩阵中的路径一样
class Solution {
public:
bool exist(vector<vector<char>>& board, string word) {
if (board.empty() || board[0].empty()) return false;
int m = board.size(), n = board[0].size();
vector<vector<bool>> visited(m, vector<bool>(n, false));
for (int i = 0; i < m; i++){
for (int j = 0; j < n; j++){
if (dfs(board, word, visited, 0, i, j)){
return true;
}
}
}
return false;
}
private:
bool dfs(vector<vector<char>>& board, string word, vector<vector<bool>>&visited,
int cur,int row,int col){
if (cur == word.size()){
return true;
}
bool found = false;
if (row >= 0 && row < board.size() && col >= 0 && col < board[0].size() &&
!visited[row][col] && board[row][col] == word[cur]){
visited[row][col] = true;
found = dfs(board, word, visited, cur + 1, row, col - 1) ||
dfs(board, word, visited, cur + 1, row, col + 1) ||
dfs(board, word, visited, cur + 1, row - 1, col) ||
dfs(board, word, visited, cur + 1, row + 1, col);
if (!found)
visited[row][col] = false;
}
return found;
}
};