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
,
"SEE"
, -> returns
true
,
"ABCB"
, -> returns
false
.
// DFS. (compare it with BFS for better understanding.)
#include <vector> #include <iostream> #include <string> using namespace std; void checkValid(vector< vector<char> >& board, int i, int j, string word, int k, vector< vector<bool> >& visited, bool& found) { if(found) return; if(k == word.size()) {found = true; return;} vector< vector<int> > direction { {0, 1}, {0, -1}, {1, 0}, {-1, 0}}; for(int x = 0; x < direction.size(); ++x) { int nextPos_x = i + direction[x][0]; int nextPos_y = j + direction[x][1]; if(nextPos_x >= 0 && nextPos_x < board.size() && nextPos_y >= 0 && nextPos_y < board[i].size()) { if(!visited[nextPos_x][nextPos_y] && board[nextPos_x][nextPos_y] == word[k]) { visited[nextPos_x][nextPos_y] = true; checkValid(board, nextPos_x, nextPos_y, word, k + 1, visited, found); visited[nextPos_x][nextPos_y] = false; } } } } // construct letters of sequentially adjacent cell. bool exist(vector< vector<char> >& board, string word) { if(board.size() == 0) return false; if(board[0].size() == 0) return false; int m = board.size(); int 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(board[i][j] == word[0]) { visited[i][j] = true; bool found = false; checkValid(board, i, j, word, 1, visited, found); if(found) return true; visited[i][j] = false; } } } return false; } int main(void) { vector< vector<char> > board { {'A', 'B', 'C', 'E'}, {'S', 'F', 'C', 'S'}, {'A', 'D', 'E', 'E'}}; bool found = exist(board, "BFCE"); cout << found << endl; }