Problem
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
.
解题思路:
本题的目的是考查图的深度优先搜索问题。从一个起点出发可以有4个方向到达下一个点,一次搜索的复杂度是O(E+V),对于本题而言一个点的搜索复杂度是O(m*n),因此总的时间复杂度是O(m*n)*O(m*n)=O(m^2*n^2),具体解题代码如下:
class Solution {
public:
bool exist(vector<vector<char>>& board, string word) {
if (word == "")
return true;
if (board.size() == 0 || board[0].size() == 0)
return false;
vector<bool> tmp(board[0].size(), false);
vector<vector<bool>> used(board.size(), tmp);
for (int i = 0; i < board.size(); i++)
{
for (int j = 0; j < board[0].size(); j++)
{
if (search(board, word, 0, i, j, used))
return true;
}
}
return false;
}
bool search(vector<vector<char>>& board, string word, int index, int i, int j, vector<vector<bool>>& used)
{
if (index == word.length())
return true;
if (i<0 || j<0 || i >= board.size() || j >= board[0].size() || used[i][j] || board[i][j] != word[index])
return false;
used[i][j] = true;
bool res = search(board, word, index + 1, i - 1, j, used)
|| search(board, word, index + 1, i + 1, j, used)
|| search(board, word, index + 1, i, j - 1, used)
|| search(board, word, index + 1, i, j + 1, used);
used[i][j] = false;
return res;
}
};