79. 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
,
word = "SEE"
, -> returns true
,
word = "ABCB"
, -> returns false
.
题目大意:
给定一个二维平面和一个单词,找出该单词是否存在于网格中。
这个词可以由顺序相邻单元格的字母构成,其中“相邻”单元格是那些水平或垂直相邻的单元格。同一个字母单元格可能不会使用一次以上。
解题思路:
需要先考虑临界状态,以及结束标志,然后剩下的使用一个d[4][2]数组表示上下左右去搜索。采用深搜dfs方式。也是比较基础的一道题。
class Solution {
public:
vector<vector<bool> > flag;
int d[4][2]={{0,1},{1,0},{0,-1},{-1,0}};
int n,m;
bool IntArry(int x,int y){
return x>=0&&y>=0&&x<m&&y<n;
}
bool searchRes(vector<vector<char> >& board,string word,int index,int startx,int starty){
int newx,newy;
if(index==word.size()-1){
return board[startx][starty]==word[index];
}
if(board[startx][starty]==word[index]){
flag[startx][starty] = true;
for(int i=0;i<4;i++){
newx = startx+d[i][0];
newy = starty+d[i][1];
if(IntArry(newx,newy)&&!flag[newx][newy]){
searchRes(board,word,index+1,newx,newy);
}
}
flag[startx][starty] = false;
}
return false;
}
bool exist(vector<vector<char> >& board, string word) {
n=board.size(); //行
m=board[0].size(); //列
flag = vector<vector<bool> >(n,vector<bool>(m,false));
for(int i=0;i<n;i++)
for(int j=0;j<m;j++)
if(searchRes(board,word,0,i,j))
return true;
return false;
}
};
结果:429ms 计算速度不够高,有待优化