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;
    }
    };
  • 相关阅读:
    P2009 跑步
    P3916 图的遍历
    P2865 [USACO06NOV]路障Roadblocks
    P2820 局域网
    P2176 [USACO14FEB]路障Roadblock
    讨伐!数论
    网络流入门——EK算法
    最被低估的特质
    我的天哪我有博客了!
    Area POJ
  • 原文地址:https://www.cnblogs.com/Vae1990Silence/p/4281452.html
Copyright © 2011-2022 走看看