• 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:
        bool Sub(vector<vector<char> >&board,string& word,int index,int i,int j,vector<vector<bool> > &used){
            if(index==word.length())return true;
            if(i>=1&&!used[i-1][j]){
                used[i-1][j]=true;
                if(board[i-1][j]==word[index]&&Sub(board,word,index+1,i-1,j,used))return true;
                used[i-1][j]=false;
            }
            if(i<board.size()-1&&!used[i+1][j]){
                used[i+1][j]=true;
                if(board[i+1][j]==word[index]&&Sub(board,word,index+1,i+1,j,used))return true;
                used[i+1][j]=false;
            }
            if(j>=1&&!used[i][j-1]){
                used[i][j-1]=true;
                if(board[i][j-1]==word[index]&&Sub(board,word,index+1,i,j-1,used))return true;
                used[i][j-1]=false;
            }
            if(j<board[0].size()-1&&!used[i][j+1]){
                used[i][j+1]=true;
                if(board[i][j+1]==word[index]&&Sub(board,word,index+1,i,j+1,used))return true;
                used[i][j+1]=false;
            }
            return false;
        }
        bool exist(vector<vector<char> > &board, string word) {
            // Note: The Solution object is instantiated only once and is reused by each test case.
            if(word=="")return false;
            if(board.size()==0||board[0].size()==0)return false;
            vector<vector<bool> > used;
            vector<bool> one;
            one.resize(board[0].size(),false);
            used.resize(board.size(),one);
            for(int i=0;i<board.size();i++){
                for(int j=0;j<board[i].size();j++){
                    used[i][j]=true;
                    if(board[i][j]==word[0]&&Sub(board,word,1,i,j,used))return true;
                    used[i][j]=false;
                }
            }
            return false;
        }
    };
    View Code
  • 相关阅读:
    Android ble 蓝牙4.0 总结
    Java byte数据类型详解
    Cocos2d-X在SwitchControl使用
    【翻译mos文章】Linux x86 and x86-64 系统SHMMAX最大
    poj 2478 Farey Sequence(欧拉函数是基于寻求筛法素数)
    Akka FSM 源代码分析
    HDU 4828 (卡特兰数+逆)
    [JSP][JSTL]页面调用函数--它${fn:}内置函数、是推断字符串是空的、更换车厢
    android 中国通信乱码问题
    Recall(检出率)和 Precision(准确性)
  • 原文地址:https://www.cnblogs.com/superzrx/p/3349490.html
Copyright © 2020-2023  润新知