POJ3984

简单搜索,用一个结构体栈来储存临时路径,一个结构体数组来存储最短路径,实时更新最短路径的结构体数组,最后输出

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define N 5

struct step {
    int tx;
    int ty;
}s[10000], t[10000];

int sizee = sizeof(t);

int maze[N][N];
int cou, minn;  ///cou 为栈顶,minn为走的最小步数

int next[4][2] = { {-1, 0}, {1, 0}, {0, 1}, {0, -1} };   ///上下左右四个方向

bool check(int x, int y)  ///检查是否标记过,是否越界
{
    if (x >= N || x < 0 || y >= N || y <0 || maze[x][y]) return false;
    return true;
}

void dfs(int x, int y, int dep)  ///dep标记走的步数
{
    int i;

    if (dep > minn) return ;   ///剪枝,当途中步数大于最小步数的时候没必要继续了

    if (x == 4 && y == 4) {  ///若抵达终点且步数小于minn,更新minn,并将栈拷贝到数组,若无更小最后输出s
        if (dep < minn) {

            minn = dep;

            memcpy(s, t, sizee);

        }
        return ;
    }

    for (i = 0; i < 4; i++) {

        int nx = x + next[i][0];
        int ny = y + next[i][1];

        if (!check(nx, ny)) continue;  ///越界与标记检查

        t[cou].tx = nx;     ///入栈
        t[cou++].ty = ny;

        maze[nx][ny] = 1;   ///标记为已经走过

        dfs(nx, ny, dep + 1);  ///dfs

        maze[nx][ny] = 0;   ///回溯
        cou--;  ///伴随回溯,弹出栈顶元素
    }
}

int main()
{
    int i, j;
    int x = 0, y = 0;
    for (i = 0; i < N; i++) {
        for (j = 0; j < N; j++) {
            scanf("%d", &maze[i][j]);
        }
    }

    cou = 0;
    minn = 99999999;

    t[cou].tx = x;    ///将(0, 0)先入栈
    t[cou++].ty = y;

    maze[0][0] = 1;   ///标记起点
    dfs(x, y, 1);  ///1刚好也是栈内元素数

    for (i = 0; i < minn; i++) {
        printf("(%d, %d)\n", s[i].tx, s[i].ty);    ///此时s内储存的就是最短路径
    }

    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值