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;
        }
    };
  • 相关阅读:
    09-排序1 排序
    06-图3 六度空间
    06-图2 Saving James Bond
    06-图1 List Components
    04-树5 Complete Binary Search Tree
    03-树2 Tree Traversals Again
    PAT 05-树8 Huffman Codes
    Egret引擎的visible两次开关闭问题
    Egret的项目笔记(一)
    Egret屏幕适配【转】
  • 原文地址:https://www.cnblogs.com/qiaozhoulin/p/4528975.html
Copyright © 2011-2022 走看看