zoukankan      html  css  js  c++  java
  • 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 }
  • 相关阅读:
    python 去重
    怎样稳稳获得年化高收益
    module_loader.py
    mac上安装ta-lib
    mac上安装memcache
    创建widget
    smartsvn 用法
    用nifi executescript 生成3小时间隔字符串
    TclError: no display name and no $DISPLAY environment variable
    【C#】详解C#序列化
  • 原文地址:https://www.cnblogs.com/cane/p/3909886.html
Copyright © 2011-2022 走看看