qq_57931996 2022-01-10 15:15 采纳率: 88.9%

# 迷宫求解，代码已写出，帮看看问题在哪里？

###### 问题相关代码，请勿粘贴截图
``````//迷宫求解
#include"stdio.h"
#include"stdlib.h"
typedef struct SNode
{
int x, y;
struct SNode* next;
}SNode;
typedef struct
{
SNode* top;
SNode* head;
}LinkStack;
void InitStack(LinkStack* S)
{
S->top = S->head = NULL;
}
void Push(LinkStack* S, int i, int j)
{
SNode* r;
r = (SNode*)malloc(sizeof(SNode));
r->x = i;
r->y = j;
r->next = NULL;
if (S->top == NULL)
S->head = S->top = r;
else
{
r->next = S->top;
S->top = r;
}
}
void Pop(LinkStack* S, int* i, int* j)
{
SNode* p;
p = S->top;
*i = p->x;
*j = p->y;
S->top = p->next;
free(p);
}
void Path(int M[][10], int x1, int y1, int x2, int y2)
{
int x, y, i, k = 0;
int px[50], py[50];
LinkStack SP;
InitStack(&SP);
x = x1;
y = y1;
while (x != x2 || y != y2)
{
M[x][y] == 2;
if (M[x][y - 1] == 0)
{
Push(&SP, x, y);
y = y - 1;
}
else if (M[x][y + 1] == 0)
{
Push(&SP, x, y);
y = y + 1;
}
else if (M[x - 1][y] == 0)
{
Push(&SP, x, y);
x = x - 1;
}
else if (M[x + 1][y] == 0)
{
Push(&SP, x, y);
x = x + 1;
}
else
Pop(&SP, &x, &y);
}
M[x][y] = 2;
Push(&SP, x, y);
printf("通过迷宫的路径为：\n");
while (SP.top != SP.head)
{
Pop(&SP, &x, &y);
px[k] = x;
py[k] = y;
k++;
}
Pop(&SP, &x, &y);
px[k] = x;
py[k] = y;
for (i = k; i >= 0; i--)
printf("(%d,%d) ", px[i], py[i]);
}
void main()
{
int x1, y1, x2, y2;
int M[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} };
printf("输入迷宫入口位置：");
scanf_s("%d,%d", &x1, &y1);
printf("输入迷宫出口位置：");
scanf_s("%d,%d", &x2, &y2);
Path(M, x1, y1, x2, y2);
}
``````

• 写回答

#### 1条回答默认 最新

• bekote 2022-01-10 16:33
关注
``````
void Path(int M[][10], int x1, int y1, int x2, int y2)
{
int x, y, i, k = 0;
int px[50], py[50];
LinkStack SP;
InitStack(&SP);
x = x1;
y = y1;
while (x != x2 || y != y2)
{
//==改成=
M[x][y] = 2;
//x和y加限制以免超出数组范围
if (y-1>0 && M[x][y - 1] == 0)
{
Push(&SP, x, y);
y = y - 1;
}
else if (y+1<9 && M[x][y + 1] == 0)
{
Push(&SP, x, y);
y = y + 1;
}
else if (x-1>0 && M[x - 1][y] == 0)
{
Push(&SP, x, y);
x = x - 1;
}
else if (x+1<9 && M[x + 1][y] == 0)
{
Push(&SP, x, y);
x = x + 1;
}
else
Pop(&SP, &x, &y);
}
M[x][y] = 2;
Push(&SP, x, y);
printf("通过迷宫的路径为：\n");
while (SP.top != SP.head)
{
Pop(&SP, &x, &y);
px[k] = x;
py[k] = y;
k++;
}
Pop(&SP, &x, &y);
px[k] = x;
py[k] = y;
for (i = k; i >= 0; i--)
printf("(%d,%d) ", px[i], py[i]);
}
``````
本回答被题主选为最佳回答 , 对您是否有帮助呢?
评论

#### 问题事件

• 已结题 （查看结题原因） 1月10日
• 已采纳回答 1月10日
• 创建了问题 1月10日

#### 悬赏问题

• ¥15 类图中关联与聚合的区别
• ¥15 ENVI高分五号去除云层的方法
• ¥15 16进制数据如何得到奇偶校验位
• ¥15 求合并两个字节流VB6代码
• ¥15 Pyqt 如何正确的关掉Qthread，并且释放其中的锁？
• ¥30 网站服务器通过node.js部署了一个项目！前端访问失败
• ¥15 WPS访问权限不足怎么解决
• ¥15 java幂等控制问题
• ¥15 海湾GST-DJ-N500
• ¥15 氧化掩蔽层与注入条件关系