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 {
    private:
        int m,n;
        int len;
        int dep;
        char** board;
        string word;
        int x,y;
        bool search()
        {
            if(dep==len) return true;
            int xnew[4];
            int ynew[4];
            xnew[0]=x;xnew[1]=x;xnew[2]=x-1;xnew[3]=x+1;
            ynew[0]=y-1;ynew[1]=y+1;ynew[2]=y;ynew[3]=y;
            for(int i=0;i<4;i++)
            if(xnew[i]>=0 && xnew[i]<m && ynew[i]>=0 && ynew[i]<n && board[xnew[i]][ynew[i]]==word[dep])
            {
                board[xnew[i]][ynew[i]]=0;
                dep++;
                x=xnew[i];y=ynew[i];
                if(search())return true;
                dep--;
                board[xnew[i]][ynew[i]]=word[dep];
            }
            return false;
        }
    public:
        bool exist(vector<vector<char> > &board, string word) 
        {
            this->word=word;
            m=board.size();
            if(m==0return false;
            n=board[0].size();
            this->board=new char*[m];
            for(int i=0;i<m;i++)
            {
                this->board[i]=new char[n];
                for(int j=0;j<n;j++)
                    this->board[i][j]=board[i][j];
            }
            
            len=word.length();
            for(int i=0;i<m;i++)
                for(int j=0;j<n;j++)
                if(this->board[i][j]==word[0])
                {
                    this->board[i][j]=0;
                    x=i;y=j;dep=1;
                    if(search())    return true;
                    this->board[i][j]=word[0];
                }
            return false;
        }
    }; 
  • 相关阅读:
    jQuery 自执行函数
    IRelationalOperator空间关系接口简介
    9.2 空间拓扑运算[转]
    解决关于ArcGIS10.2服务手动启动的问题
    Multipart to single part feature
    Multipart polyline to single part lines
    VS2015 C#6.0 中的没有实现/支持的特性
    VS2015 C#6.0 中的那些新特性
    ArcGIS中各种合并要素(Union、Merge、Append、Dissolve)的异同点分析 转载
    FME2010 案例分析: 动态批量转换
  • 原文地址:https://www.cnblogs.com/erictanghu/p/3759511.html
Copyright © 2011-2022 走看看