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 };
  • 相关阅读:
    everything is nothing
    基础算法
    OC 优化目录
    iOS 更改启动视图
    单例--iOS
    OC-Objection 学习笔记之一:简单的开始
    iOS 类库列表
    IOS 上线问题
    OC强弱引用的使用规则
    设置桌面图标
  • 原文地址:https://www.cnblogs.com/zle1992/p/10242799.html
Copyright © 2011-2022 走看看