//螺旋數(shù)組 之字形數(shù)組 /* 實(shí)現(xiàn)一個(gè)之字形數(shù)組 ,從1 開始,之字形形成數(shù)組 1 3 4 10 2 5 9 11 6 8 12 15 7 13 14 16 */ #include<stdio.h> #include <stdlib.h> //using namespace std; void constructArray(int **array,int N) { //說明,方向坐標(biāo),每兩個(gè)單位表示一個(gè)反向, //一共四個(gè)方向,比如 //direction[0]、direction[1]表示第一個(gè)方向的x 和 y的走向 //direction[2]、direction[3]表示第二個(gè)方向的x 和 y的走向 //direction[4]、direction[5]表示第三個(gè)方向的x 和 y的走向 //direction[6]、direction[7]表示第四個(gè)方向的x 和 y的走向 int direction[8]={1,0,-1,1,0,1,1,-1}; int row = 0, col = 0; bool changeDirec = false; int index = 1; array[row][col] = index; while(1) { for(int i = 0; i < 4; i++) { if (row == N-1 && col == N-1)//最后一個(gè)位置跳出 break; if(row == N-1 && N%2==1 && changeDirec==false)//奇數(shù)行換方向 { direction[0]=0; direction[1]=1; direction[2]=-1; direction[3]=1; direction[4]=1; direction[5]=0; direction[6]=1; direction[7]=-1; changeDirec = true; break; } if(col == N-1 && N%2==0 && changeDirec==false)//偶數(shù)行換方向 { direction[0]=1; direction[1]=0; direction[2]=1; direction[3]=-1; direction[4]=0; direction[5]=1; direction[6]=-1; direction[7]=1; changeDirec = true; break; } if (changeDirec==false) { if (i%2==0) { row += direction[2*i]; col += direction[2*i+1]; array[row][col] = ++index; } else { while(1) { if ((direction[2*i]+row)<0 || (col+direction[2*i+1])<0 || (direction[2*i]+row)>=N || (col+direction[2*i+1])>=N)break;//越界判斷 row += direction[2*i]; col += direction[2*i+1]; array[row][col] = ++index; } } }else { if (i%2==0) { row += direction[2*i]; col += direction[2*i+1]; array[row][col] = ++index; } else { while(1) { if ((direction[2*i]+row)<0 || (col+direction[2*i+1])<0 || (direction[2*i]+row)>=N || (col+direction[2*i+1])>=N)break;//越界判斷 row += direction[2*i]; col += direction[2*i+1]; array[row][col] = ++index; } } } } if (row == N-1 && col == N-1) break; } } int main() { int **array; int N; printf("請(qǐng)輸入數(shù)組N*N的維數(shù)N:\n"); scanf("%d",&N); //內(nèi)存分配 array = (int **)malloc(N*sizeof(int *)); if (array == NULL) { return -1; } for (int i = 0; i < N; i++) { array[i] = (int *)malloc(N*sizeof(int)); if(array[i]==NULL)return -1; } //初始化 for(int i = 0; i < N; i++) for(int j = 0; j < N; j++) { array[i][j] = 0; } constructArray(array,N); for(int i = 0; i < N; i++) { for(int j = 0; j < N; j++) { printf("%d ",array[i][j]); } printf("\n"); } //內(nèi)存釋放 for (int i = 0; i < N; i++) { free(array[i]); } free(array); return 0; }
|
|
|