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 };
  • 相关阅读:
    各种贴图
    d3d11devicecontext
    小记2
    Tom Ryaboi
    Tessellation
    关于图形学
    第一章实验
    控制输入框只接收数字及小数点
    JQuery控制文本框是否可以输入
    SQLSERVER中查询一个存储过程使用到的地方
  • 原文地址:https://www.cnblogs.com/zle1992/p/10242799.html
Copyright © 2011-2022 走看看