DFS--走迷宫

题目来源:codeup链接

#include <iostream>
#include <vector>
using namespace std;
int n, m;
const int maxn = 30;
const int maxm = 30;
int a[maxn][maxm];
int sx, sy, ex, ey;
bool vis[maxn][maxm] = {false};
bool has = false;                                         //是否存在这样一条路径
int direction[4][2] = {{0, -1}, {-1, 0}, {0, 1}, {1, 0}}; //左-上-右-下
struct path
{
    int x;
    int y;
};
vector<path> Path;
void DFS(int x, int y)
{
    if (x == ex && y == ey)
    {
        has = true;
        for (unsigned int i = 0; i < Path.size(); i++)
        {
            if (i == 0)
            {
                cout << '(' << Path[i].x << ',' << Path[i].y << ')';
            }
            else
            {
                cout << "->(" << Path[i].x << ',' << Path[i].y << ')';
            }
        }
        cout << endl;
        return;
    }
    for (int i = 0; i < 4; i++)
    {
        int nx = x + direction[i][0];
        int ny = y + direction[i][1];
        if (nx < 1 || ny < 1 || nx > n || ny > m) //判断是否越界
        {
            continue;
        }
        if (vis[nx][ny] == false && a[nx][ny] == 1)//判断是否为障碍物或已经在路径中
        {
            vis[nx][ny] = true;
            path temp;
            temp.x = nx;
            temp.y = ny;
            Path.push_back(temp);
            DFS(nx, ny);
            vis[nx][ny] = false;
            Path.pop_back();
        }
    }
}
int main()
{
    cin >> n >> m;
    for (int i = 1; i <= n; i++)
    {
        for (int j = 1; j <= m; j++)
        {
            cin >> a[i][j];
        }
    }
    cin >> sx >> sy;
    cin >> ex >> ey;
    vis[sx][sy] = true;
    path temp;
    temp.x = sx;
    temp.y = sy;
    Path.push_back(temp);
    DFS(sx, sy);
    if (!has)
    {
        cout << -1 << endl;
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值