以下是使用向量跟踪解坐标的方法:
#include <iostream>
#include <vector>
#include <map>
using namespace std;
const int w = 10, l = 10;
const char Start = 'S', Path = ' ', End = 'E', Visited = '.', Solution = '*';
char Map[w][l + 1] =
{
{ " # # # " },
{ " S # # " },
{ " ### " },
{ " # # " },
{ " # # " },
{ "# #" },
{ " ### " },
{ " ##E ## " },
{ " # " },
{ " ##### #" },
};
int Solved = false;
vector<pair<int,int> > SolutionCoors;
void PrintMap()
{
int x, y;
for (y = 0; y < w; y++)
{
for (x = 0; x < l; x++)
cout << Map[y][x];
cout << endl;
}
}
void Solve_Maze(int CoorX, int CoorY)
{
if (CoorX >= 0 && CoorX < l && CoorY >= 0 && CoorY < w && !Solved)
{
SolutionCoors.push_back(make_pair(CoorX, CoorY)); // Store potential solution
if (Map[CoorY][CoorX] == Start || Map[CoorY][CoorX] == Path)
{
Map[CoorY][CoorX] = Visited;
Solve_Maze(CoorX + 1, CoorY);
Solve_Maze(CoorX - 1, CoorY);
Solve_Maze(CoorX, CoorY + 1);
Solve_Maze(CoorX, CoorY - 1);
}
else if (Map[CoorY][CoorX] == End)
Solved = true;
if (!Solved)
SolutionCoors.pop_back();
}
}
int main()
{
PrintMap();
Solve_Maze(1, 1);
if (Solved)
{
for (vector<pair<int,int> >::iterator it = SolutionCoors.begin();
it != SolutionCoors.end();
it++)
{
cout << "(" << it->first << "," << it->second << ")" << endl; // Print solution coords
Map[it->second][it->first] = Solution; // Also mark on the map
}
PrintMap();
}
return 0;
}
输出:
# # #
S # #
###
# #
# #
# #
###
##E ##
#
##### #
(1,1)
(2,1)
(3,1)
(4,1)
(4,2)
(5,2)
(6,2)
(6,3)
(5,3)
(5,4)
(6,4)
(7,4)
(7,5)
(8,5)
(8,6)
(9,6)
(9,7)
(8,7)
(8,8)
(7,8)
(6,8)
(5,8)
(4,8)
(4,7)
# #.#..
****#..#.
###***...
#.**#..
#***#.
# **#
### **
##* ##**
#.*****.
##### #
另请注意,我Map[][]
的坐标颠倒了。