您的位置:首页 > 其它

【leetcode】Word Search

2015-01-03 19:31 190 查看

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 =

[
["ABCE"],
["SFCS"],
["ADEE"]
]

word =
"ABCCED"
, -> returns
true
,
word =
"SEE"
, -> returns
true
,
word =
"ABCB"
, -> returns
false
.

class Solution {
public:

int n,n1,n2;

bool exist(vector<vector<char> > &board, string word) {

n1=board.size();
n2=board[0].size();
n=word.length();

bool flag=false;

//vector<vector<bool> > visited(n1,vector<bool>(n2,false));

bool **visited=new bool*[n1];
for(int i=0;i<n1;i++)
{
visited[i]=new bool[n2];
for(int j=0;j<n2;j++)
{
visited[i][j]=false;
}
}

for(int i=0;i<n1;i++)
{
for(int j=0;j<n2;j++)
{
if(board[i][j]==word[0])
{
//注意visited采用引用传值
flag=flag||dfs(board,word,i,j,visited);
if(flag) return true;
}
}
}

for(int i=0;i<n1;i++) delete[] visited[i];

return false;
}

bool dfs(vector<vector<char> > &board,string &word,int i,int j,bool** &visited,int index=0)
{

if(board[i][j]!=word[index]||visited[i][j]) return false;
if(index==n-1) return true;

visited[i][j]=true;

bool flag1=i+1<n1&&dfs(board,word,i+1,j,visited,index+1);
bool flag2=j+1<n2&&dfs(board,word,i,j+1,visited,index+1);
bool flag3=j-1>=0&&dfs(board,word,i,j-1,visited,index+1);
bool flag4=i-1>=0&&dfs(board,word,i-1,j,visited,index+1);

bool result=flag1||flag2||flag3||flag4;

//由于是引用传值,所以没有找到的目标串时要把visited复原
//if(result==false) visited[i][j]=false;
visited[i][j]=result;
return result;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: