Word Search
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
,
word =
"ABCB"
, -> returns
false
.
解题技巧:
采用深度优先搜索的方法
代码:
bool Search(vector< vector<char> >& board, int m, int n, vector< vector<bool> > &flag, string word)
{
int dir[4][2] = {{-1, 0}, {0, -1}, {1, 0}, {0, 1}};
if(word.size() == 0) return true;
flag[m][n] = true;
for(int i = 0; i < 4; i++)
{
int x, y;
x = m + dir[i][0];
y = n + dir[i][1];
if(x < 0 || x >= board.size() || y < 0 || y >= board[0].size() || flag[x][y]) continue;
if(board[x][y] == word[0] && Search(board, x, y, flag, word.substr(1)) )
{
return true;
}
}
flag[m][n] = false;
return false;
}
bool exist(vector< vector<char> >& board, string word)
{
int m = board.size(), n = board[0].size();
vector< vector<bool> > flag(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] && Search(board, i, j, flag, word.substr(1)))
{
return true;
}
}
}
return false;
}