您的位置:首页 > 其它

LeetCode--Word Search

2014-08-13 13:16 405 查看
dfs

https://github.com/cane1991/BasicAlogrithmSourceCode/blob/master/LeetCode/WordSearch.cpp

/*************************************************************************
> File Name: WordSearch.cpp
> Author: zhoukang1991
> Mail: zhoukang199191@126.com
> Created Time: 2014年08月14日 星期四 00时58分49秒
************************************************************************/

#include <iostream>
#include <vector>
#include <string>
using namespace std;

class Solution{
public:
bool exist(vector<vector<char> > &board,string word){
const int row = board.size();
if(row == 0)
return false;
const int col = board[0].size();
for(int i = 0 ; i < row ; ++i){
for(int j = 0 ; j < col ; ++j){
if(board[i][j] == word[0] && dfs(i,j,word,0,board))
return true;
}
}
return false;
}
bool dfs(int row,int col,string &word,int index,vector<vector<char> > &board){
if(index = word.size()-1)
return true;
char ctmp = board[row][col];
board[row][col] = '.';

//left right up down dfs
if(col-1 >= 0 && board[row][col-1] == word[index+1]){
if(dfs(row,col-1,word,index+1,board)){
return true;
}
}
if(col+1 <= board[0].size() && board[row][col+1] == word[index+1]){
if(dfs(row,col+1,word,index+1,board)){
return true;
}
}
if(row-1 >= 0 && board[row-1][col] == word[index+1]){
if(dfs(row-1,col,word,index+1,board))
return true;
}
if(row+1 <= board[0].size() && board[row+1][col] == word[index+1]){
if(dfs(row+1,col,word,index+1,board))
return true;
}
}
};

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