标签:迷宫
迷宫问题的解决方法主要是利用栈,对于入口处开始当遍历数为0时,就将这个数压入栈底,并将这个数改为2,当一条通路已经找到最远处,却没有到最底,这个时候就要回溯,将有些数弹出栈。
#define N 10
struct pos
{
int _row;
int _col;
};
void GetMaze(int *a, int n)
{
FILE *fout = fopen("Maze.txt", "r");
for (int i = 0; i < N;i++)
for (int j = 0; j < N;)
{
char ch = fgetc(fout);
if (ch == ‘0‘ || ch == ‘1‘)
{
a[i*N + j] = ch - ‘0‘;
j++;
}
else
{
continue;
}
}
fclose(fout);
}
void print(int *a, int n)
{
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
{
cout << a[i*N + j] << " ";
}
cout << "\n";
}
}
bool check(int *a,pos next)
{
if (next._row >= 0 && next._row < N&&next._col >= 0 && next._col < N&&a[next._row*N + next._col] == 0)
return true;
return false;
}
bool MazePath(int *a, int n, pos &entry, stack<pos>&path)
{
pos man = entry;
path.push(man);
while (!path.empty())
{
if (man._row == N - 1)
{
return true;
}
a[man._row*N + man._col] = 2;
pos next = man;
next._row--;
if (check((int*)a, next))
{
man = next;
path.push(man);
continue;
}
next = man;
next._row++;
if (check((int*)a, next))
{
man = next;
path.push(man);
continue;
}
next = man;
next._col--;
if (check((int*)a, next))
{
man = next;
path.push(man);
continue;
}
next = man;
next._col++;
if (check((int*)a, next))
{
man = next;
path.push(man);
continue;
}
man = path.top();
path.pop();
}
}
void Test()
{
int a[N][N] = {};
GetMaze((int *)a, N);
print((int *)a, N);
stack<pos>p;
pos entry = { 2, 0 };
cout<<MazePath((int *)a, N, entry, p);
}
int main()
{
Test();
getchar();
return 0;
}
标签:迷宫
原文地址:http://10810512.blog.51cto.com/10800512/1762401