[Algoritmo de retroceso] problema de laberinto clásico

detalles del tema

problema del laberinto

tren de pensamiento

Usamos el método de retroceder para resolver este problema y exploramos en cuatro direcciones sin pensar. Si podemos caminar, continuaremos explorando hasta salir del laberinto. Explorar otras direcciones.
inserte la descripción de la imagen aquí
Código marco:

Para evitar confusiones causadas por demasiados parámetros de la función de retroceso, se recomienda declarar la matriz, la fila y la columna como variables globales.

#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;

Código de núcleo de retroceso:

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();
}

Código de referencia

#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;
}

Supongo que te gusta

Origin blog.csdn.net/m0_73209194/article/details/130179927
Recomendado
Clasificación