[Backtracking algorithm] classic maze problem

topic details

maze problem

train of thought

We use the method of backtracking to solve this problem, and explore in four directions without thinking. If we can walk, we will continue to explore until we get out of the maze. Explore other directions.
insert image description here
Framework code:

In order to avoid confusion caused by too many backtracking function parameters, it is recommended to declare the array, row and column as global variables.

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int ROW,COL;
vector<vector<int>> maze;
vector<vector<int>> path_tmp;
vector<vector<int>> path_bst;

Backtracking core code:

void backTrack(int i,int j)
{
    
    
    maze[i][j] = 1;//表示已经走过这里了

    path_tmp.push_back({
    
    i,j});
    
    //判断是否走到最后
    if(i == ROW-1 && j == COL-1)
    {
    
    
        if(path_bst.empty() || path_tmp.size() < path_bst.size())
        {
    
    
            path_bst = path_tmp;
        }
    }

    //右
    if(j+1 < COL && maze[i][j+1] == 0)
        backTrack(i, j+1);
    //上
    if(i-1 >= 0 && maze[i-1][j] == 0)
        backTrack(i-1, j);
    //下
    if(i+1 < ROW && maze[i+1][j] == 0)
        backTrack(i+1, j);
    //左
    if(j-1 >= 0 && maze[i][j-1] == 0)
        backTrack(i, j-1);

    //无路可走就回溯了
    maze[i][j] = 0;
    path_tmp.pop_back();
}

Reference Code

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int ROW,COL;
vector<vector<int>> maze;
vector<vector<int>> path_tmp;
vector<vector<int>> path_bst;


void backTrack(int i,int j)
{
    
    
    maze[i][j] = 1;

    path_tmp.push_back({
    
    i,j});
    
    //判断是否走到最后
    if(i == ROW-1 && j == COL-1)
    {
    
    
        if(path_bst.empty() || path_tmp.size() < path_bst.size())
        {
    
    
            path_bst = path_tmp;
        }
    }

    //右
    if(j+1 < COL && maze[i][j+1] == 0)
        backTrack(i, j+1);
    //上
    if(i-1 >= 0 && maze[i-1][j] == 0)
        backTrack(i-1, j);
    //下
    if(i+1 < ROW && maze[i+1][j] == 0)
        backTrack(i+1, j);
    //左
    if(j-1 >= 0 && maze[i][j-1] == 0)
        backTrack(i, j-1);

    //无路可走就回溯了
    maze[i][j] = 0;
    path_tmp.pop_back();
}
int main() 
{
    
    
    while(cin >> ROW >> COL)
    {
    
    
        //构造迷宫
        maze = vector<vector<int>> (ROW,vector<int> (COL,0));
        for(int i = 0;i<ROW;i++)
            for(int j = 0;j<COL;j++)
            cin >> maze[i][j];

        //从0,0开始寻找

        backTrack(0,0);
        
        for(int i = 0;i<path_bst.size();i++)
        {
    
    
            printf("(%d,%d)\n",path_bst[i][0],path_bst[i][1]);
        }
        path_bst.clear();
        path_tmp.clear();

    }
    return 0;
}

Guess you like

Origin blog.csdn.net/m0_73209194/article/details/130179927