The sword refers to the path in the OFFER 12 matrix

1. Description of the topic

Given an mxn two-dimensional character grid board and a string word word. Returns true if word exists in the grid; otherwise, returns false.

Words must be formed alphabetically, through letters in adjacent cells, where "adjacent" cells are those that are horizontally or vertically adjacent. Letters in the same cell are not allowed to be used repeatedly.

example

insert image description here

problem solving ideas

This question is a typical matrix search problem, which can be solved using depth-first search (DFS) + pruning.

  • Depth-first search, brute force search for every possible path, starting from the upper left corner, first search in one direction, if you encounter an unequal point, return to the previous equal point or starting point, and continue traversing in a new direction.
  • Direction dirs{ {0,1},{0,-1},{1,0},{-1,0}}:{down, up, right, left}, before the traversal starts, judge if the node continues to traverse Whether it will exceed the boundary. If it is within the boundary, first judge whether the new node has been traversed, and if it has been traversed, continue to the new node in the next direction. Use a visite[i][j] to record the nodes traversed in this round. Set the node to false when backtracking;
  • Pruning : In the search, if the path cannot match the given string successfully, it should be returned immediately, which is called feasible pruning.

insert image description here

class Solution {
    
    
private:
    int row;
    int col;
    bool check(vector<vector<char>>& board,string s,int i,int j,int k){
    
    
        if(i < 0 || i >= row || j <0 || j >= col || board[i][j] != s[k]) return false;
        if(k == s.size()-1) return true;
        board[i][j] = '\0';//遍历过的位置改成空格做标记
        bool res = check(board,s,i,j+1,k+1) || check(board,s,i,j-1,k+1) ||check(board,s,i+1,j,k+1) || check(board,s,i-1,j,k+1);
                   
        board[i][j] = s[k];//回溯
        return res;
    }
public:
    bool exist(vector<vector<char>>& board, string word) {
    
    
        row = board.size();
        col = board[0].size();
        for(int i = 0;i < row;i++){
    
    
            for(int j = 0;j < col;j++){
    
    
                if(check(board,word,i,j,0)) return true;
            }
        }
        return false;
    }
};

Guess you like

Origin blog.csdn.net/qq_43679351/article/details/125005368