一種螺旋隊列的描述:
21 22 23 24 。。
20 7 8 9 10
19 6 1 2 11
18 5 4 3 12
17 16 15 14 13
這是一個順時針的螺旋數列,設1的座標是(0,0),取x的正方向為向右,取y的正方向為向下。則7的座標就是(-1,-1),2的座標是(0,1),3的座標是(1,1)。
現在需要編程實現:
1,輸入一個座標輸出對應的數字;
2,輸入一個數字輸出對應的座標。
代碼如下:
#include <stdio.h><br />int step=0;<br />int key=1;<br />int N=0;<br />typedef struct<br />{<br />int x;<br />int y;<br />}node;<br />node A[100];<br />int temp_x=0,temp_y=0;<br />int x,y=0;<br />bool Isexsit();<br />bool Isaim();<br />int main()<br />{<br />printf("1.輸入座標->輸出對應的數(預設)/n2.輸入數字->輸出對應的座標/n");<br />input:<br />printf("請選擇模式:");<br />scanf("%d",&key);<br />if(key==1)<br />{<br />printf("輸入座標值:");<br />scanf("%d%d",&x,&y);<br />}<br />else if(key==2)<br />{<br />printf("輸入數字:");<br />scanf("%d",&N);<br />}<br />else<br />{<br />printf("Error Operation/n");<br />goto input;<br />}<br />while(1)<br />{<br />operation1:<br />temp_x++;step++;<br />if(!Isexsit())<br />{<br />A[step].x=temp_x;<br />A[step].y=temp_y;<br />if(Isaim())<br />break;<br />}<br />else if(Isexsit())<br />{<br />temp_x--;step--;<br />goto operation4;<br />}<br />operation2:<br />temp_y++;step++;<br />if(!Isexsit())<br />{<br />A[step].x=temp_x;<br />A[step].y=temp_y;<br />if(Isaim())<br />break;<br />}<br />else if(Isexsit())<br />{<br />temp_y--;step--;<br />goto operation1;<br />}<br />operation3:<br />temp_x--;step++;<br />if(!Isexsit())<br />{<br />A[step].x=temp_x;<br />A[step].y=temp_y;<br />if(Isaim())<br />break;<br />}<br />else if(Isexsit())<br />{<br />temp_x++;step--;<br />goto operation2;<br />}<br />operation4:<br />temp_y--;step++;<br />if(!Isexsit())<br />{<br />A[step].x=temp_x;<br />A[step].y=temp_y;<br />if(Isaim())<br />break;<br />}<br />else if(Isexsit())<br />{<br />temp_y++;step--;<br />goto operation3;<br />}<br />}<br />if(key==1)<br />printf("%d/n",step+1);<br />else<br />printf("%d %d/n",temp_x,temp_y);<br />return 0;<br />}<br />bool Isexsit()<br />{<br />int i=0;<br />while(i<50)<br />{<br />if(A[i].x==temp_x&&A[i].y==temp_y)<br />return true;<br />i++;<br />}<br />return false;<br />}<br />bool Isaim()<br />{<br />if(key==1)<br />{<br />if(temp_x==x&&temp_y==y)<br />return true;<br />else return false;<br />}<br />else //key==2<br />{<br />if(step+1==N)<br />return true;<br />else return false;<br />}<br />}<br />
運行結果如下:
歡迎各路牛人批評指正~