#include <stdio.h>
#define huadian 1
#define wenjudian 2
#define tiyu 3
#define MAX 9
void nearst(int x,int y,int type); //最近算法
void check1(int x,int y,int x1,int y1,int type); //搜索周围可能最近的商店
void check2(int x,int y,int x1,int y1,int type); //确定最近的商店
int s[MAX+1][MAX+1]={0}; //用二维数组模拟的坐标
int min=65535;
void main(void)
{
int x=4; //用户的坐标x
int y=4; //用户的坐标y
int type=0; //商店类型
s[4][2]=huadian; //初始化坐标地图
s[2][4]=huadian;
s[2][7]=huadian;
s[6][2]=wenjudian;
s[6][7]=wenjudian;
s[4][5]=tiyu;
s[4][6]=tiyu;
s[9][9]=tiyu;
printf("input your address:"); //界面设计
scanf("%d %d",&x,&y);
printf("/nshop type(1:huadian,2:wenjudian,3:tiyu):");
scanf("%d",&type);
if(s[x][y]==type)
printf("the nearst shop in x=%d,y=%d",x,y);
else
nearst(x,y,type);
getchar();
getchar();
}
void nearst(int x,int y,int type)
{
int x1=x; /*移动地址*/
int y1=y-1;
int x2=x; /*每次起始地址*/
int y2=y1;
int i=0;
while(min == 65535)
{ /*转圈搜索*/
i++;
for(;x1>=x-i && x1>=0 && x1<=MAX;x1--)
check1(x,y,x1,y1,type);
for(x1++,y1++;y1<=y+i && y1>=0 && y1<=MAX;y1++)
check1(x,y,x1,y1,type);
for(y1--,x1++;x1<=x+i && x1>=0 && x1<=MAX;x1++)
check1(x,y,x1,y1,type);
for(x1--,y1--;y1>=y2 && y1>=0 && y1<=MAX;y1--)
check1(x,y,x1,y1,type);
for(y1++,x1--;x1>x2 && x1>=0 && x1<=MAX;x1--)
check1(x,y,x1,y1,type);
y1=--y2;
x1=x2;
}
/*从x2 y2 开始转圈*/
y1=++y2;
x1=x2;
for(;x1>=x-i && x1>=0 && x1<=MAX;x1--)
check2(x,y,x1,y1,type);
for(x1++,y1++;y1<=y+i && y1>=0 && y1<=MAX;y1++)
check2(x,y,x1,y1,type);
for(y1--,x1++;x1<=x+i && x1>=0 && x1<=MAX;x1++)
check2(x,y,x1,y1,type);
for(x1--,y1--;y1>=y2 && y1>=0 && y1<=MAX;y1--)
check2(x,y,x1,y1,type);
for(y1++,x1--;x1>x2 && x1>=0 && x1<=MAX;x1--)
check2(x,y,x1,y1,type);
}
void check1(int x,int y,int x1,int y1,int type) //搜索可能最近的商店
{
if(s[x1][y1]==type)
{
if(((x1-x)*(x1-x)+(y1-y)*(y1-y))<min)
{
min=(x1-x)*(x1-x)+(y1-y)*(y1-y);
}
}
}
void check2(int x,int y,int x1,int y1,int type) //确定最近商店
{
if(((x1-x)*(x1-x)+(y1-y)*(y1-y))==min && s[x1][y1]==type)
{
printf("the nearst shop in x=%d,y=%d/n",x1,y1);
}
}