LeetCode--Word Search

dfs

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

 1 /*************************************************************************
 2     > File Name: WordSearch.cpp
 3     > Author: zhoukang1991
 4     > Mail: zhoukang199191@126.com 
 5     > Created Time: 2014年08月14日 星期四 00时58分49秒
 6  ************************************************************************/
 7 
 8 #include <iostream>
 9 #include <vector>
10 #include <string>
11 using namespace std;
12 
13 class Solution{
14     public:
15         bool exist(vector<vector<char> > &board,string word){
16             const int row = board.size();
17             if(row == 0)
18                 return false;
19             const int col = board[0].size();
20             for(int i = 0 ; i < row ; ++i){
21                 for(int j = 0 ; j < col ; ++j){
22                     if(board[i][j] == word[0] && dfs(i,j,word,0,board))
23                         return true;
24                 }
25             }
26             return false;
27         }
28         bool dfs(int row,int col,string &word,int index,vector<vector<char> > &board){
29             if(index = word.size()-1)
30                 return true;
31             char ctmp = board[row][col];
32             board[row][col] = '.';
33 
34             //left right up down dfs
35             if(col-1 >= 0 && board[row][col-1] == word[index+1]){
36                 if(dfs(row,col-1,word,index+1,board)){
37                     return true;
38                 }
39             }
40             if(col+1 <= board[0].size() && board[row][col+1] == word[index+1]){
41                 if(dfs(row,col+1,word,index+1,board)){
42                     return true;
43                 }
44             }
45             if(row-1 >= 0 && board[row-1][col] == word[index+1]){
46                 if(dfs(row-1,col,word,index+1,board))
47                     return true;
48             }
49             if(row+1 <= board[0].size() && board[row+1][col] == word[index+1]){
50                 if(dfs(row+1,col,word,index+1,board))
51                     return true;
52             }
53         }
54 };
55 
56 int main()
57 {
58     return 0;
59 }

 

转载于:https://www.cnblogs.com/cane/p/3909886.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值