关于栈、越界:此程序为啥一直显示停止工作?
开始运行先提示用户输入彩球个数n(0<n≤81),然后随机选取颜色和位置填充棋盘,输出填充后的棋盘状态。接下来,提示用户输入指定彩球的坐标(fx,fy)以及目标空位(tx,ty)(0≤fx,fy,tx,ty≤8),如果起点没有彩球,或者目标不是空位,需要提示错误并重新输入。
坐标以左上角为(0,0),第一个分量为行,后一个分量为列。
本题要求使用栈完成。
#if defined(WIN32) || defined(WIN64)
#include <windows.h>
#define sleep(n) Sleep(1000 * (n))
#endif
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int flag;
int x1,y1;
typedef struct{
int x;
int y;
} locate;
typedef struct {
locate *buf; //数据区
int top; //栈顶指针
int m; //栈大小
} stack;
void init_stack(stack *s, int size) {
s->buf = ( locate*) malloc(size * sizeof(locate));
s->top = -1;
s->m = size;
}
void push(stack *s, int x,int y) {
if (s->top == s->m - 1) return;
s->top = s->top + 1;
(s->buf[s->top]).x = x;
(s->buf[s->top]).y = y;
}
void pop(stack *s, int *x,int *y) {
if (s->top == -1) return;
*x = (s->buf[s->top]).x;
*y = (s->buf[s->top]).y;
s->top = s->top - 1;
}
int is_empty(stack *s) {
return (s->top == -1);
}
void top(stack *s, int *x,int *y) {
if (s->top == -1) return;
*x = (s->buf[s->top]).x;
*y = (s->buf[s->top]).y;
}
int main()
{
void judge(int m,int n,int x,int y,int a[9][9]);
int i,j,count=0,m,n,x,y;
int a[9][9]={0};
printf("Please write the amount of ball:");
scanf("%d",&n);
srand((unsigned) time(NULL));
while(count<n)//填充随机数1是球球,0是空位
{
i= rand()%9;
j=rand()%9;
while(a[i][j]==1)
{
i= rand()%9;
j=rand()%9;
}
a[i][j]=1;
count++;
};
for(i=0;i<9;i++)//打印
for(j=0;j<9;j++)
{
printf("%d ",a[i][j]);
if(j==8) printf("\n");
}
printf("Please write the original location:");
scanf("%d,%d",&m,&n);
if (a[m][n]==0) {printf("fail!");return 0;}
printf("Please write the target location:");
scanf("%d,%d",&x,&y);
judge(m,n,x,y,a);
if(flag==1) printf("success!");
else printf("fail!");
return 0;
}
void judge(int m,int n,int x,int y,int a[9][9])
{
flag=0;
stack s;
init_stack(&s, 100);
int i,j;
i=m,j=n;
if((i==x)&(j==y)) flag=1;
while(!(a[i][j+1]&&a[i+1][j]&&a[i][j-1]&&a[i-1][j]))//如果四周都是球就退出了
{
if(a[i][j+1]==0&&(is_empty(&s)||!((i==x1)&&(j+1==y1)))&&(j>=0&&j<=7))
//如果(上面是空的)&&上一步不是往上走&&往上走不会溢出
{
j++;s.top++;push(&s,i,j);
}
else if(a[i+1][j]==0&&(is_empty(&s)||!((i+1==x1)&&(j==y1)))&&(i>=0&&i<=7))
{
i++;s.top++;push(&s,i,j);
}
else if(a[i][j-1]==0&&(is_empty(&s)||!((i==x1)&&(j-1==y1)))&&(j>=1&&j<=8))
{
j--;s.top++;push(&s,i,j);
}
else if(a[i-1][j]==0&&(is_empty(&s)||!((i-1==x1)||(j==y1)))&&(i>=1&&i<=8))
{
i--;s.top++;push(&s,i,j);
}
else
{
a[i][j]=1;pop(&s,&i,&j);
}
if((i==x)&&(j==y)) {
flag=1;
break;}
top(&s,&x1,&y1);//保存这次的行走坐标,给下次使用
}
}
我是新手,很菜,我知道这大概是那几种情况,可找不出具体是哪种我无从下手改动,麻烦各位帮我看下,谢谢