有一个X*Y的网格,只能向右、向下移动,从(0, 0)走到(X-1, Y-1),中间某些位置有障碍物,打印一条路径(优化)

#include <list>
#include <iostream>
#include<map>
using namespace std;

int maze[4][4] = {1,1,1,0,1,1,0,1,1,1,1,1,0,0,1,1};//0表示障碍,1表示可以通过

struct Point
{
    int x;
    int y;   
    bool operator < (const Point& p) const
    {
        if (this->x < p.x)
        {
            return true;
        }
        else if (this->x == p.x && this->y < p.y)
        {
            return true;
        }
        return false;
    }
};

bool getPath(int x, int y, list<Point>& path, map<Point, bool>& cache)
{
    Point p = {x, y};
    if (cache.find(p) != cache.end())
    {
        return cache.at(p);
    }
    path.push_back(p);  
    if (x == 0 && y == 0)//逆序打印路径,从(x,y)走到(0,0)
    {
        for (list<Point>::iterator iter = path.begin(); iter != path.end(); iter++)
        {
            cout << "(" << iter->x << "," << iter->y << ")";
            if (iter->x == 0 && iter->y == 0)
            {
            }
            else
            {
                cout  << " -> ";
            }                       
        }
        cout << endl;       
        return true;
    }
    bool res = false;
    if (x >= 1 && maze[x-1][y] == 1)
    {
        res = getPath(x-1, y, path, cache);            
    }
    if (!res)
    {
        if (y >= 1 && maze[x][y-1] == 1)
        {
            res = getPath(x, y-1, path, cache);              
        }   
    }  
    if (!res)
    {
        path.pop_back();
    }
    cache[p] = res;  
    return res;
}

int main()
{
    list<Point> path;
    map<Point, bool> cache;
    path.clear();
    cache.clear();
    getPath(3, 3, path, cache);
    getchar();
    return 0;
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值