问题描述
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.
Example:
board =
[
[‘A’,’B’,’C’,’E’],
[‘S’,’F’,’C’,’S’],
[‘A’,’D’,’E’,’E’]
]
Given word = “ABCCED”, return true.
Given word = “SEE”, return true.
Given word = “ABCB”, return false.
题目链接:
思路分析
给一个二维char数组和一个word,判断word能否由数组中连续的相邻的字母组成。
循环数组每一个位置的字母,递归判断由它开始,是否能够组成word。
递归开始,有若干结束条件,如果len == word.length()了,那么就是word中的字符都已经判断完成了,返回true;如果i或j越界了,返回false;如果board[i][j]不是对应word位置的字符,返回fasle。这些都满足的情况下,再对i,j位置周围的四个位置进行判断,递归调用existWord,返回调用的结果。
要注意的是,在进行BFS之前,要对已访问的节点进行标记,事后要再恢复,否则之后的搜索会出错。在代码中将它换成一个非字母的值就行。
代码
class Solution {
public:
bool exist(vector<vector<char>>& board, string word) {
for (int i = 0; i < board.size(); i++){
for (int j = 0; j < board[0].size(); j++){
if (existWord(board, i, j, word, 0))
return true;
}
}
return false;
}
bool existWord(vector<vector<char>>& board, int i, int j, string word, int len){
if (len == word.size()) return true;
if (i < 0 || j < 0 || i == board.size() || j == board[0].size())
return false;
if (board[i][j] != word[len])
return false;
char temp = board[i][j];
board[i][j] = '*';
bool exist = existWord(board, i - 1, j, word, len+1) ||
existWord(board, i, j - 1, word, len+1) ||
existWord(board, i + 1, j, word, len+1) ||
existWord(board, i, j + 1, word, len+1);
board[i][j] = temp;
return exist;
}
};
时间复杂度:
O(m∗n)
空间复杂度:
O(m∗n)
反思
又有点像我的人工智能项目了。如果知道可以重置恢复这一手,我就不用那么麻烦弄两个数组了。