LeetCode--word-search(矩阵方格中单词的查找bfs应用)

版权声明:本文为自学而写,如有错误还望指出,谢谢^-^ 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;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_43871369/article/details/91436779