zoukankan      html  css  js  c++  java
  • 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 isExist(vector<vector<char>>& board,string wordsub,int h,int w, vector<vector<bool>>&flag)
        {
            int direct[4][2]={{0,1},{0,-1},{1,0},{-1,0}};
            for(int d=0;d<4;d++)
            {
                int jj=h+direct[d][0];
                int ii=w+direct[d][1];
                if(jj>=0&&jj<board.size()&&ii>=0&&ii<board[0].size())
                {
                    if(wordsub[0]==board[jj][ii]&&flag[jj][ii]==0)
                    {
                        flag[jj][ii]=1;
                        if(wordsub.size()==1||isExist(board,wordsub.substr(1),jj,ii,flag))
                            return true;
                        flag[jj][ii]=0;
                    }
                    
                }
                    
            }
            return false;
        }
       
        bool exist(vector<vector<char>>& board, string word) {
            int length=word.size();
            int Height=board.size();
            int Width=board[0].size();
            vector<vector<bool>> flag(Height,vector<bool>(Width,0));
            for(int h=0;h<Height;h++)
                for(int w=0;w<Width;w++)
                {
                    if(board[h][w]==word[0])
                    {
                        flag[h][w]=1;
                        if( word.size()==1||isExist(board,word.substr(1),h,w,flag))
                            return true;
                        flag[h][w]=0;
                    }
                }
            return false;
        }
    };
  • 相关阅读:
    代码习惯
    全网最详细的fhq treap (非旋treap)讲解
    按位或「HAOI2015」
    列队「NOIP2017」
    愤怒的小鸟「NOIP2016」
    能量传输「CSP多校联考 2019」
    矿物运输「CSP多校联考 2019」
    普通打击「CSP多校联考 2019」
    普通快乐「CSP多校联考 2019」
    BZOJ4385: [POI2015]Wilcze doły
  • 原文地址:https://www.cnblogs.com/qiaozhoulin/p/4528975.html
Copyright © 2011-2022 走看看