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 };
  • 相关阅读:
    关于Android线程间通信
    关于代码重构
    Android读书笔记01
    回忆 2012年写的
    我的笑 -- 2007年写的?
    伊人笑 2010年
    血色青春 2012年
    隔夜听雨
    错乱的爱 2010年
    【前端JS、后台C#】编码解码。
  • 原文地址:https://www.cnblogs.com/zle1992/p/10242799.html
Copyright © 2011-2022 走看看