zoukankan      html  css  js  c++  java
  • 79. Word Search

    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.

    Example:

    board =
    [
      ['A','B','C','E'],
      ['S','F','C','S'],
      ['A','D','E','E']
    ]
    
    Given word = "ABCCED", return true.
    Given word = "SEE", return true.
    Given word = "ABCB", return false.
    
     1 class Solution {
     2 public:
     3     bool exist(vector<vector<char>>& board, string word) {
     4         for(int i = 0;i < board.size();i++){
     5             for(int j =0;j<board[0].size();j++){
     6                 bool res = dfs(board,i,j,word,0);
     7                 if(res) return true;
     8             }
     9         }
    10         return false;
    11     }
    12     bool dfs(vector<vector<char>>& board, int i,int j,string word,int cur_len){
    13         if(cur_len>=word.size()) return true;
    14         if(i<0||j<0||i>=board.size()||j>=board[0].size()) return false;
    15         if(board[i][j]==word[cur_len]){
    16             char c = board[i][j];
    17             board[i][j]='+';
    18             bool res = dfs(board,i,j-1,word,cur_len+1)||
    19                        dfs(board,i-1,j,word,cur_len+1)||
    20                       dfs(board,i+1,j,word,cur_len+1)||   
    21                       dfs(board,i,j+1,word,cur_len+1);
    22             board[i][j] = c;
    23             return res;
    24         }
    25         else
    26             return false;
    27     }
    28 };
  • 相关阅读:
    C++引用之引用的使用
    C++引用之声明方法
    C++const与指针
    C++默认参数值函数
    LeanCloud 调研报告
    [译] 为何流处理中局部状态是必要的
    Z-Stack
    Think twice before starting the adventure
    Multi-pattern string match using Aho-Corasick
    C pointer again …
  • 原文地址:https://www.cnblogs.com/zle1992/p/10242799.html
Copyright © 2011-2022 走看看