Word Search

来源:互联网 发布:知乎 网页版 编辑:程序博客网 时间:2024/05/01 11:32

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.

pro:给一个board,判断一个单词是否出现在board中,出现的方式是从一个字母开始,沿着上一个字母的邻居(上下左右)走,如果能匹配到单词的最后一个字母,表示这个单词出现,返回true,否则返回false.
sol:从board中找到一个跟word[0]匹配的切入点,开始dfs,dfs时向上下左右dfs,用used记录某一个点是否被访问过,每次递归回溯将used再设置为没访问过。当匹配到word结尾时,返回true。值得注意的是怎么保证一旦有一个返回true,就不做其他的了。就是dfs下一层时,如果下一层返回的是true,那么这一层也返回true,不做下面的了。
值得注意的是,这道题之前一直一直tle。明明思路是对的,在隔了很久之后突然realize自己一个stupid的地方,vector传入参数时,么有加&,导致后面一直tle。。。之前遇到过一题,这下长了记性。
code:
class Solution{private:int n,m;public:bool exist(vector< vector<char> > &board,string word){if(word.length()==0) return true;int dir[4][2]={0,1,0,-1,1,0,-1,0};int i,j,k;n=board.size();if(n==0) return false;m=board[0].size();if(m==0) return false;vector< vector<bool> > used(n,vector<bool>(m,false));int index;index=0;for(i=0;i<n;i++){for(j=0;j<m;j++){if(board[i][j]==word[0]){used[i][j]=true;if(dfs(dir,board,word,i,j,used,index+1)) return true;//chang du wei 1!!!!!!used[i][j]=false;}}}return false;}bool isok(int tempx,int tempy,int n,int m,vector< vector<bool> > &used){if(tempx>=0&&tempx<n&&tempy>=0&&tempy<m&&used[tempx][tempy]==false)return true;else return false;}bool dfs(int dir[4][2],vector< vector<char> > &board,string word,int x,int y,vector< vector<bool> > &used,int index){if(index==word.length()){return true;}int i,tempx,tempy;for(i=0;i<4;i++){tempx=x+dir[i][0];tempy=y+dir[i][1];if(isok(tempx,tempy,n,m,used)&&board[tempx][tempy]==word[index]){used[tempx][tempy]=true;if(dfs(dir,board,word,tempx,tempy,used,index+1))    return true;used[tempx][tempy]=false;}}return false;}};


0 0
原创粉丝点击