zoukankan      html  css  js  c++  java
  • leetcode[79]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 check(vector<vector<char> > &board, string word, vector<vector<int>> &beUsed, int i, int j, int index)
    {
        if (index==word.size())return true;
        int direction[4][2]={{-1,0},{1,0},{0,-1},{0,1}};
        for (int k=0;k<4;k++)
        {
            int ii=i+direction[k][0];
            int jj=j+direction[k][1];
            if(ii>=0&&ii<board.size()&&jj>=0&&jj<board[0].size()&&!beUsed[ii][jj]&&board[ii][jj]==word[index])
            {
                beUsed[ii][jj]=1;
                if(check(board,word,beUsed,ii,jj,index+1))return true;
                beUsed[ii][jj]=0;
            }
        }
        return false;
    }
    bool exist(vector<vector<char> > &board, string word) 
    {
        if(word.size()==0)return true;
        vector<vector<int>> beUsed(board.size(),vector<int> (board[0].size(),0));
        for (int i=0;i<board.size();i++)
        {
            for (int j=0;j<board[i].size();j++)
            {
                if (board[i][j]==word[0])
                {
                    beUsed[i][j]=1;
                    if (check(board, word, beUsed, i, j, 1))return true;
                    beUsed[i][j]=0;
                }
            }
        }
        return false;
    }
    };
  • 相关阅读:
    Python之路,day16-Python基础
    Python之路,day15-Python基础
    Python之路,day14-Python基础
    django之model操作
    django信号
    django缓存
    CSRF的攻击与防范
    cookie和session
    http协议之Request Headers
    ajax参数详解
  • 原文地址:https://www.cnblogs.com/Vae1990Silence/p/4281452.html
Copyright © 2011-2022 走看看