#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define Max 100
typedef struct {
int row, col;
int data;
int di;//方向 1右 2下 3左 4上
int printFeet;//是否走过 0没走过 1走
}MazeNode;
typedef struct {
MazeNode data[Max];
int top;
}Stack;
void InitStack(Stack &s) {
s.top = -1;
}
bool IsEmpty(Stack &s) {
if (s.top == -1) {
return true;
}
return false;
}
bool Overflow(Stack &s) {
if (s.top == Max -1) return true;
return false;
}
bool Push(Stack &s, MazeNode x) {
if (Overflow(s)) return false;
s.data[++s.top] = x;
return true;
}
bool Pop(Stack &s, MazeNode &x) {
if (IsEmpty(s)) return false;
x = s.data[s.top--];
return true;
}
MazeNode Top(Stack &s) {
return s.data[s.top];
}
void InitMaze(int arr[10][10],MazeNode Maze[10][10]) {
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
Maze[i][j].row = i;
Maze[i][j].col = j;
Maze[i][j].data = arr[i][j];
Maze[i][j].di = 1;
Maze[i][j].printFeet = 0;
}
}
}
void PrintPath(MazeNode Maze[10][10],int row,int col) {
Maze[row][col].printFeet = 1;
}
MazeNode nextNode(MazeNode Maze[10][10],int &i ,int &j) {
if (Maze[i][j].di != 5 &&Maze[i][j].data != 1) {
if (Maze[i][j].di == 1) {
Maze[i][j].di++;
j++;
}
else if (Maze[i][j].di == 2) {
Maze[i][j].di++;
i++;
}
else if (Maze[i][j].di == 3) {
Maze[i][j].di++;
j--;
}
else {
Maze[i][j].di++;
i--;
}
}
return Maze[i][j];
}
void printMaze(MazeNode Maze[10][10]) {
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
if (Maze[i][j].data == 2 || Maze[i][j].data == 0) {
printf(" ");
}
else {
printf(" × ");
}
}
printf("\n");
}
}
void printFeet(MazeNode Maze[10][10]) {
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
if (Maze[i][j].printFeet == 1) {
printf(" ");
}
else {
printf(" × ");
}
}
printf("\n");
}
}
void MazePath(MazeNode Maze[10][10], Stack s,MazeNode start,MazeNode end) {
int i = start.row, j = start.col;
Push(s, Maze[i][j]);
PrintPath(Maze, i, j);
MazeNode p;
p.row = start.row;
p.col = start.col;
while (Maze[p.row][p.col ].row != end.row || Maze[p.row ][p.col ].col != end.col ) {
//寻找下一个点
nextNode(Maze, p.row, p.col);
//下一个点是否合格
if (Maze[p.row][p.col].printFeet == 0 && Maze[p.row][p.col].data == 0) {
//合格则入栈
Push(s, Maze[p.row][p.col]);
PrintPath(Maze, p.row, p.col);
}
else {
//不合格则读取栈顶指针
p = Top(s);
}
//如果当前栈顶的结点是不通的,则将此节点出栈
while (Maze[p.row][p.col].di == 5) {
Pop(s, p);
}
}
while (!IsEmpty(s)) {
Pop(s, p);
Maze[p.row][p.col].data = 2;
}
printf("结束后\n");
printMaze(Maze);
printf("探索过的地方\n");
printFeet(Maze);
}
int main() {
int a[10][10] =
{ { 1,1,1,1,1,1,1,1,1,1 },
{ 1,0,0,1,0,0,0,1,0,1 },
{ 1,0,0,1,0,0,0,1,0,1 },
{ 1,0,0,0,0,1,1,0,0,1 },
{ 1,0,1,1,1,0,0,0,0,1 },
{ 1,0,0,0,1,0,0,0,0,1 },
{ 1,0,1,0,0,0,1,0,0,1 },
{ 1,0,1,1,1,0,1,1,0,1 },
{ 1,1,0,0,0,0,0,0,0,1 },
{ 1,1,1,1,1,1,1,1,1,1 } };
MazeNode Maze[10][10];
InitMaze(a, Maze);
printf("迷宫为:\n");
printMaze(Maze);
Stack s;
InitStack(s);
MazeNode start, end;
start.row = start.col = 1;
end.row = end.col = 8;
MazePath(Maze, s, start, end);
getchar();
}
5(栈的应用)迷宫求解
最新推荐文章于 2023-01-12 08:37:18 发布