现在的位置: 首页 > 综合 > 正文

word search

2017年12月23日 ⁄ 综合 ⁄ 共 1244字 ⁄ 字号 评论关闭

题目描述如下:

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.

最开始朝DP去想了下没有结果,于是还是用最暴力的回溯来做了:

class Solution {
public:
int m,n;
vector<vector<int> >* visit;
    bool exist(vector<vector<char> >& board,string word)
{
         m=board.size();
	if (m==0)
		return word.empty()||word[0]=='\0';
	if (word.empty()||word[0]=='\0')
		return true;
	n=board[0].size();
         vector<vector<int> > v=vector<vector<int> >(m,vector<int>(n,0));
         visit=&v;
	int i,j;
	for(i=0;i<m;i++)
	{
		for(j=0;j<n;j++)
		{
				if( _exist(board,word,0,i,j))
					return true;
		}
	}
        return false;
}
bool _exist(vector<vector<char> >& board,string& word,int kth,int i,int j)
{
	if (board[i][j]!=word[kth]||(*visit)[i][j]==1)
		return false;
         if ( kth==word.size()-1)
            return true;
	(*visit)[i][j]=1;
	bool ans=false;
	if ( i>0 )
	{
		ans=_exist(board,word,kth+1,i-1,j);
		if (ans )
			return true;
	}
	if ( i<m-1 )
	{
		ans=_exist(board,word,kth+1,i+1,j);
		if (ans ) return true;
	}
	if (j>0)
	{
		ans=_exist(board,word,kth+1,i,j-1);
		if (ans) return true;
	}
	if (j<n-1)
	{
		ans=_exist(board,word,kth+1,i,j+1);
		if (ans) return true;
	}
	(*visit)[i][j]=0;
	return false;
}
		


};

 

抱歉!评论已关闭.