Stack复习-迷宫输出一条路径,用栈实现

迷宫的试探与回溯,对应于压栈与出栈过程。

试探与回溯,深度遍历的过程,不保证输出的一条路径就是最短路径,广度遍历可以。

//
//  main.cpp
//  stack
//
//  Created by scnulpc on 2018/10/11.
//  Copyright © 2018年 scnulpc. All rights reserved.
//

#include <iostream>
#include <stack>
#define max 100
using namespace std;
//算法输出迷宫的一条路径
//map[][]迷宫的地图
//sign[][]迷宫的标志
int map[max][max];
int sign[max][max];
struct item
{
    int x;
    int y;
    string step;
    item(int a,int b,string c)
    {
        x=a;y=b;step = c;
    }
};
struct offset
{
    int a,b;
    offset(int x,int y)
    {
        a=x;b=y;
    }
};
offset* Move[8]={new offset(-1,0),new offset(-1,1),new offset(0,1),new offset(1,1),new offset(1,0),new offset(1,-1),new offset(0,-1),new offset(-1,-1)};
void path(int row,int column)
{
    stack<item*> s ;item* current;item* forhead;
    int i,j,g,h;//(i,j)当前坐标,(g,h) 下一步坐标
    item *start = new item(1,1,"(1,1)->");
    s.push(start);
    sign[1][1]=1;
    
    while (!s.empty())
    {
        current = s.top();
        forhead = current;
        s.pop();
        i=current->x;
        j=current->y;
        int d=0;
        while (d<8)
        {
            g=i+Move[d]->a;
            h=j+Move[d]->b;
            if (g==row&&h==column)
            {
                cout<<forhead->step+"(";
                cout<<g;
                cout<<",";
                cout<<h;
                
                cout<<")"<<endl;
                return ;
            }
            else if (map[g][h]==0&&sign[g][h]==0)
            {
                sign[g][h]=1;
                i=g;
                j=h;
                d=0;
                forhead = new item(g,h,forhead->step+"("+to_string(i)+","+to_string(j)+")"+"->");
                s.push(forhead);
                
            }
            else d++;
        }
    }
    
    cout<<"no way"<<endl;
}
void init()
{
    memset(map, 1, sizeof(map));
    memset(sign, 0, sizeof(sign));
}
int main(int argc, const char * argv[])
{
    init();
    int n,m;
    cout<<"输入地图n行 m列"<<endl;
    cin>>n>>m;
    for (int i=1; i<=n; i++)
    {
        for (int j=1; j<=m; j++)
        {
            cin>>map[i][j];
        }
    }
    path(5, 4);
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值