#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;
}
有一个X*Y的网格,只能向右、向下移动,从(0, 0)走到(X-1, Y-1),中间某些位置有障碍物,打印一条路径(优化)
最新推荐文章于 2024-04-16 10:50:22 发布