LeetCode - word-search (matrix grid of words to find bfs application)

Disclaimer: This article is written self-study, pointed out that if the error also hope, thank you ^ - ^ https://blog.csdn.net/weixin_43871369/article/details/91436779

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:
    int offset[4][2]={1,0,0,1,-1,0,0,-1};
    int state[102][102]={0};
    int index=0;
    bool exist(vector<vector<char> > &board, string word) {
        for(int i=0;i<board.size();++i)
            for(int j=0;j<board[0].size();++j)
            {
                if(board[i][j]==word[0]&&SeekPath(board,word,i,j))
                    return true;
            }
        return false;
    }
 private:
    bool SeekPath(vector<vector<char> > &board,string word,int x,int y)
    {
         state[x][y]=1;
        ++index;
        if(index==word.size()) return true;
        for(int i=0;i<4;++i)
        {
            int tempx=x+offset[i][0];
            int tempy=y+offset[i][1];
            if(tempx<0||tempx>=board.size()||tempy<0||tempy>=board[0].size()||state[tempx][tempy])
                continue;
            if(board[tempx][tempy]==word[index]&&SeekPath(board,word,tempx,tempy))
               return true;
        }
        --index;
        state[x][y]=0;
        return false;
    }
};

 

Guess you like

Origin blog.csdn.net/weixin_43871369/article/details/91436779