您的位置:首页 > 其它

[leetcode] Word Search

2013-08-16 11:10 351 查看
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
.

这道题目用的是DFS的思想

class Solution {
struct pos{
int i;
int j;
pos(int _i , int _j):i(_i),j(_j){}
};
private:
int m;
int n;
public:
bool exist(vector<vector<char> > &board, string word) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
m=board.size();
n=board[0].size();
vector<bool> flagt(n,false);
bool (*flag)[100]=new bool[m][100];
memset(flag,0,sizeof(bool)*m*100);
int length=word.size();
int wordp;
for(int i=0 ; i<m ; i++){
for(int j=0 ; j<n ; j++){
wordp=0;
if(board[i][j]==word[0] && DFS(board,pos(i,j),flag,word,wordp))
return true;
memset(flag,0,sizeof(bool)*m*100);
}
}
return false;
}
bool DFS(vector<vector<char> > &board, pos cur, bool flag[][100], string &word,int p){
if(p==word.size())
return true;
int i,j;
i=cur.i,j=cur.j;
if(i<0 || j<0 || i>=m || j>=n)
return false;
if(flag[i][j]==true)
return false;
flag[i][j]=true;
if(board[i][j]!=word[p]){
flag[i][j]=false;
return false;
}
if(DFS(board,pos(i+1,j),flag,word,p+1))
return true;
if(DFS(board,pos(i,j-1),flag,word,p+1))
return true;
if(DFS(board,pos(i-1,j),flag,word,p+1))
return true;
if(DFS(board,pos(i,j+1),flag,word,p+1))
return true;
return false;
}
};




                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: