#include <iostream> #include <stdlib.h> #include <time.h> using namespace std; int main(){ srand(time(NULL)); cout<<"請輸入列數 : "; int n; scanf("%d", &n); cout<<"請輸入一開始的方向, 0左, 1上, 2右, 3下 : "; int dir; scanf("%d", &dir); int **d=new int*[n]; bool **b=new bool*[n]; for (int i=0;i<n;i++){ d[i]=new int[n]; b[i]=new bool[n]{0}; for (int j=0;j<n;j++){ d[i][j]=rand()%100; } } for (int i=0;i<n;i++){ for (int j=0;j<n;j++){ printf("%02d ", d[i][j]); } printf("\n"); } printf("\n"); int x=n/2, y=n/2; int nx, ny; int xd[4]={-1, 0, 1, 0}; int yd[4]={0, -1, 0, 1}; int count=0; while(count<n*n){ printf("%02d ", d[y][x]); b[y][x]=true; nx=x+xd[dir]; ny=y+yd[dir]; if(b[ny][nx]){ dir=(dir+3)%4; nx=x+xd[dir]; ny=y+yd[dir]; } count++; x=nx; y=ny; dir=(dir+1)%4; } }