zoukankan      html  css  js  c++  java
  • LeetCode 79. 单词搜索

    题目链接:https://leetcode-cn.com/problems/word-search/

    给定一个二维网格和一个单词,找出该单词是否存在于网格中。

    单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母不允许被重复使用。

    示例:

    board =
    [
    ['A','B','C','E'],
    ['S','F','C','S'],
    ['A','D','E','E']
    ]

    给定 word = "ABCCED", 返回 true
    给定 word = "SEE", 返回 true
    给定 word = "ABCB", 返回 false
     

    提示:

    board 和 word 中只包含大写和小写英文字母。
    1 <= board.length <= 200
    1 <= board[i].length <= 200
    1 <= word.length <= 10^3

     1 class Solution {
     2 public:
     3     bool dfs(vector<vector<char>>& board,string& word,int index,int x,int y){
     4         if(index==word.length()) return true;
     5         if(board[x][y]!=word[index]) return false;
     6         char tmp=board[x][y];
     7         board[x][y]='.';
     8         if(x>0&&dfs(board,word,index+1,x-1,y)) return true;
     9         if(x<board.size()-1&&dfs(board,word,index+1,x+1,y)) return true;
    10         if(y>0&&dfs(board,word,index+1,x,y-1)) return true;
    11         if(y<board[0].size()-1&&dfs(board,word,index+1,x,y+1)) return true;
    12         board[x][y]=tmp;
    13         return false;
    14     }
    15     bool exist(vector<vector<char>>& board, string word) {
    16         if(board.size()==0) return false;
    17         if(board.size()==1&&board.size()==1&&word.length()==1) return board[0][0]==word[0];
    18         for(int i=0;i<board.size();i++){
    19             for(int j=0;j<board[0].size();j++){
    20                 if(dfs(board,word,0,i,j)) return true;
    21             }
    22         }
    23         return false;
    24     }
    25 };
  • 相关阅读:
    随便写的,关于外部提交按钮
    thinkPHP--empey标签
    ramdajs库应用场景
    数组常用用法--map,filter,reduce
    接口签名
    四种常见的 POST 提交数据方式
    localhost、127.0.0.1和0.0.0.0和本机IP的区别
    ftp与sftp
    本地已有项目上传git
    github和gitlab比较
  • 原文地址:https://www.cnblogs.com/shixinzei/p/12682204.html
Copyright © 2011-2022 走看看