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 };
  • 相关阅读:
    javaweb
    反射 day1
    JDBC-day1
    总结
    day5
    day4
    day3
    18.10.17 考试总结
    洛谷P2172 [bzoj] 2150 部落战争
    18.10.15 考试总结
  • 原文地址:https://www.cnblogs.com/zle1992/p/10242799.html
Copyright © 2011-2022 走看看