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.
给一个字符矩阵和一个字符序列,判断序列在不在这个矩阵中,查找时只能邻近查找(上下左右)。
方法:上下左右做四条搜索路径,递归调用。
class Solution {
private:
bool help(int i, int j, vector<vector<char>>& board, string word, int pos){
if(pos==word.size()) return true;//注意当条件为pos==word.size()时才能判断到word的最后一个元素
if(i<0||i>=board.size()||j<0||j>=board[0].size()||word[pos]!=board[i][j]) return false;
char ch = board[i][j];
board[i][j]='\0';//判断过的元素设为'\0'防止重新判断
if(help(i-1,j,board,word,pos+1)||
help(i+1,j,board,word,pos+1)||
help(i,j-1,board,word,pos+1)||
help(i,j+1,board,word,pos+1)) return true;
board[i][j] = ch;
return false;
}
public:
bool exist(vector<vector<char>>& board, string word) {
int pos = 0;
for(int i=0;i<board.size();i++)
for(int j=0;j<board[0].size();j++){
if(help(i,j,board,word,pos)) return true;
}
return false;
}
};
自己刚开始想的也是查找四条路径,但是没有用递归,所以四条路径不是同时搜索的,最后导致有的数据判断不正确。也把代码写下来,做一个警示吧。
class Solution {
public:
bool exist(vector<vector<char>>& board, string word) {
vector<vector<int>> path;
int last_step=0;
int count = 0;
vector<int> tem(2);
for(int i=0;i<board.size();i++){
for(int j=0;j<board[0].size();j++){
if(board[i][j]==word[0]){
path.clear();
last_step = 0;
count = 0;
int tem_i = i,tem_j = j;
int last_count;
while(tem_i<board.size()&&tem_j<board[0].size()&&count!=word.size()-1){
last_count=count;
//up
if(last_step != 2){
if(tem_i>0){
tem[0]=tem_i-1;
tem[1]=tem_j;
vector<vector<int>>::iterator index = find( path.begin(), path.end(), tem);
if(board[tem_i-1][tem_j]==word[count+1]&&(index==path.end())){
tem_i--;
count++;
path.push_back(tem);
last_step=1;
}
}
}
//down
if(last_step != 1){
if(tem_i<board.size()-1){
tem[0]=tem_i+1;
tem[1]=tem_j;
vector<vector<int>>::iterator index = find( path.begin(), path.end(), tem);
if(board[tem_i+1][tem_j]==word[count+1]&&(index==path.end())){
tem_i++;
count++;
path.push_back(tem);
last_step=2;
}
}
}
//left
if(last_step != 4){
if(tem_j>0){
tem[0]=tem_i;
tem[1]=tem_j-1;
vector<vector<int>>::iterator index = find( path.begin(), path.end(), tem);
if(board[tem_i][tem_j-1]==word[count+1]&&(index==path.end())){
tem_j--;
count++;
path.push_back(tem);
last_step=3;
}
}
}
//right
if(last_step != 3){
if(tem_j<board[0].size()-1){
tem[0]=tem_i;
tem[1]=tem_j+1;
vector<vector<int>>::iterator index = find( path.begin(), path.end(), tem);
if(board[tem_i][tem_j+1]==word[count+1]&&(index==path.end())){
tem_j++;
count++;
path.push_back(tem);
last_step=4;
}
}
}
if(last_count==count) break;
}
if(count==word.size()-1) return true;
}
}
}
return false;
}
};