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 }
  • 相关阅读:
    Java读写配置文件prop.properties
    java中int转String 固定位数 不足补零
    plantix插件工具,eclipse工具
    MongoDB API java的使用
    CSS定位细节
    Mysql 基于BinaryLog的复制
    Mysql之复制服务
    Linux 中文乱码问题解决
    Maven中手动引用第三方jar包
    innodb之超时参数配置
  • 原文地址:https://www.cnblogs.com/cane/p/3909886.html
Copyright © 2011-2022 走看看