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 =
[
["ABCE"],
["SFCS"],
["ADEE"]
]
word = "ABCCED", -> returns true,
word = "SEE", -> returns true,
word = "ABCB", -> returns false.
解题报告:
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 =
[
["ABCE"],
["SFCS"],
["ADEE"]
]
word = "ABCCED", -> returns true,
word = "SEE", -> returns true,
word = "ABCB", -> returns false.
解题报告:
开始时使用bfs,超时,后来改为dfs就通过了
#include<iostream>
#include<vector>
#include<set>
using namespace std;
class Solution {
public:
bool exist(vector<vector<char> > &board, string word) {
if(word.length()==0)
return true;
if(board.size()==0)
return false;
int m = board.size();
int n = board[0].size();
if( word.length() > m*n )
return false;
for(int i=0;i<m;++i){
for(int j=0;j<n;++j){
if(board[i][j]==word[0]){
Pos pos;
pos.i=i;
pos.j=j;
vector<Pos> vpos;
vpos.push_back(pos);
if(dfs(board,word,1,i,j,vpos))
return true;
}
}
}
return false;
}
struct Pos{
int i,j;
};
bool dfs(vector<vector<char> > &board,string word,int word_index,int i,int j,vector<Pos> &vpos){
if(word_index>=word.length())
return true;
int dir[4][2]={{1,0},{-1,0},{0,1},{0,-1}};
int m = board.size();
int n = board[0].size();
for(int k=0;k<4;++k){
int ni = i + dir[k][0];
int nj = j + dir[k][1];
if(ni>=0&&ni<m&&nj>=0&&nj<n&&board[ni][nj]==word[word_index]){
//not appare
bool find = false;
for(int i0=0;i0<vpos.size();++i0){
if(ni==vpos[i0].i&&nj==vpos[i0].j){
find=true;
break;
}
}
if(find)
continue;
Pos pos;
pos.i=ni;
pos.j=nj;
vpos.push_back(pos);
if(dfs(board,word,word_index+1,ni,nj,vpos))
return true;
vpos.pop_back();
}
}
return false;
}
};
int main(){
vector<vector<char> > board;
vector<char> vchar0;
vchar0.push_back('A');
vchar0.push_back('B');
vchar0.push_back('C');
vchar0.push_back('E');
board.push_back(vchar0);
vector<char> vchar1;
vchar1.push_back('S');
vchar1.push_back('F');
vchar1.push_back('C');
vchar1.push_back('S');
board.push_back(vchar1);
vector<char> vchar2;
vchar2.push_back('A');
vchar2.push_back('D');
vchar2.push_back('E');
vchar2.push_back('E');
board.push_back(vchar2);
Solution s;
cout<<s.exist(board,"ABCE")<<endl;
cout<<s.exist(board,"SEE")<<endl;
cout<<s.exist(board,"ABCB")<<endl;
cout<<s.exist(board,"A")<<endl;
cout<<s.exist(board,"DA")<<endl;
cout<<s.exist(board,"M")<<endl;
}