problem:
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
,"SEE"
, -> returns true
,"ABCB"
, -> returns false
.thinking:
(1)确定方法:全局搜索满足条件的解,使用DFS
(2)深搜成功的条件是:深搜成功一次,步数+1,直到深搜的步数达到word的长度
(3)新开一个矩阵大小的二维数组,记录矩阵的字符是否用过,先在矩阵中搜索word[0]的位置,一次为起点开始深搜,每次搜索上下左右四个方向
code:
class Solution { private: bool flag; public: bool exist(vector<vector<char> > &board, string word) { int m=board.size(); int n=board[0].size(); int Maxdep=word.size(); flag = false; vector<int> a1(n,0); vector<vector<int> > array(m,a1); for(int i=0;i<m;i++) //寻找搜索起点 { for(int j=0;j<n;j++) { if(flag) //加快搜索 return true; if(board[i][j]==word[0]) dfs(0,Maxdep,i,j,array,board,word); } } return flag; } protected: void dfs(int dep,int Maxdep,int x, int y,vector<vector<int> > &array, vector<vector<char> > &board, string word) { if(flag) //不能去掉,去掉就超时了 return; int m=board.size(); int n=board[0].size(); if(dep==Maxdep) //这个必须放在x,y 边界判断的前面 { flag=true; return ; } if(x<0 || x>=m || y<0 || y>=n) return; if(array[x][y]==1) return; if(board[x][y]==word[dep]) //四个方向深搜 { array[x][y]=1; dfs(dep+1,Maxdep,x-1,y,array,board,word); dfs(dep+1,Maxdep,x,y-1,array,board,word); dfs(dep+1,Maxdep,x+1,y,array,board,word); dfs(dep+1,Maxdep,x,y+1,array,board,word); array[x][y]=0; } } };
原文地址:http://blog.csdn.net/hustyangju/article/details/44976867