Leetcode79 Word Search

Title Description

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.

Example:

board =
[
['A','B','C','E'],
['S','F','C','S'],
['A','D','E','E']]

Given word = "ABCCED", return true.
Given word = "SEE", return true.
Given word = "ABCB", return false.

Source: stay button (LeetCode)
link: https://leetcode-cn.com/problems/word-search

Code

class Solution {
public:
    bool existCore(vector<vector<char>>& board, string &word,int & Wordpos,int rows,int cols,int row,int col,vector<vector<int> > & visited){
        if(Wordpos>=word.size())
            return true;
        if(col>=cols||row>=rows||col<0||row<0){
            return false;
        }
        bool flag=false;
        if(board[row][col]==word[Wordpos]&& visited[row][col]!=1){
           ++Wordpos;
 visited[row][col]=1;           
            flag=existCore(board,word,Wordpos,rows,cols,row+1,col,visited)||existCore(board,word,Wordpos,rows,cols,row,col+1,visited)||existCore(board,word,Wordpos,rows,cols,row-1,col,visited)||existCore(board,word,Wordpos,rows,cols,row,col-1,visited);
            if(!flag)
            {
                --Wordpos;
                visited[row][col]=0;
            }
        }
        return flag;
    }
    bool exist(vector<vector<char>>& board, string word) {
        bool result=false;
        if(board.size()==0||board[0].size()==0){
            return false;
        }
        int rows=board.size();
        int cols=board[0].size();
        vector<vector<int> > visited;
        for(int i=0;i<rows;++i){
            vector<int> temp;
            for(int j=0;j<cols;++j){
                temp.push_back(0);
            }
            visited.push_back(temp);
        }
        int Wordpos=0;
        for(int i=0;i<rows;++i){
            for(int j=0;j<cols;++j)
            {
                if(existCore(board,word,Wordpos,rows,cols,i,j,visited))
                    return true;
            }
        }
        return false;
    }
};

to sum up

The idea is backtracking. Middle tangled a bit, visited the array is a two-dimensional array or a vector. If later found with two-dimensional array, where pass pointer is more trouble and can not be like a vector directly visited [row] [col].

Guess you like

Origin www.cnblogs.com/HaoPengZhang/p/11587327.html