问题遇到的现象和发生背景
问题相关代码,请勿粘贴截图
//迷宫求解
#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);
}
运行结果及报错内容
我的解答思路和尝试过的方法
我想要达到的结果