zoukankan      html  css  js  c++  java
  • Leetcode 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.

    For example,
    Given board =

    [
      ["ABCE"],
      ["SFCS"],
      ["ADEE"]
    ]
    

    word = "ABCCED", -> returns true,
    word = "SEE", -> returns true,
    word = "ABCB", -> returns false

     本题用深度搜索即可

    class Solution {
    public:
        typedef vector<vector<bool> > VVB;
        typedef vector<vector<char> > VVC;
        
        const int dx[4] = {0,1,0,-1};
        const int dy[4] = {1,0,-1,0};
        
        int n,m;
        VVC board;
        string word;
        
        bool dfs(int x, int y,int index,VVB &visit){
            if(index == word.length()) return true;
            if(x>=0 && x <n && y>=0 && y < m && !visit[x][y] && board[x][y] == word[index]){
                visit[x][y] = true;
                for(int i = 0 ; i < 4; ++ i){
                    if(dfs(x+dx[i], y+dy[i],index+1,visit)) return true;
                }
                visit[x][y] = false;
            }
            return false;
        }
    
        bool exist(VVC &board, string word) {
            this->board = board;
            this->word = word;
            n = board.size();
            m = board[0].size();
            VVB visit(n,vector<bool>(m,false));
            for(int i = 0 ; i < n; ++i ){
                for(int j = 0 ; j < m ;++ j){
                    if(dfs(i,j,0,visit)) return true;
                }
            }
            return false;
        }
    };
  • 相关阅读:
    查找二叉树(BST)
    利用堆计算中位数
    java文件的上传与下载通用版
    input框checkBox全选单选js操作,后台取值
    ArrayList源码简单解析
    echarts柱状图的学习01
    Oracle中的存储过程,存储函数
    简单的Oracle分页公式
    入门级的SSM架构搭建解析
    mybatis动态Sql详解
  • 原文地址:https://www.cnblogs.com/xiongqiangcs/p/3826258.html
Copyright © 2011-2022 走看看