1 //使用gcc完成一个matrix 2 //要求输入两个整数m,n ,得到一个螺旋矩阵。 3 //如输入3,4返回 4 //A B C D 5 //J K L E 6 //I H G F 7 8 #include <stdio.h> 9 #include <string.h> 10 const int ROW_SIZE = 10; 11 const int COLUMN_SIZE =10; 12 13 int main() 14 { 15 int array[ROW_SIZE][COLUMN_SIZE]; 16 memset(array, 0, sizeof(array)); 17 int i,j; 18 19 int x = 0; 20 int y = 0; 21 int M,N; 22 printf("请输入M,N "); 23 scanf("%d%d",&M,&N); 24 int totalStep = M*N; 25 /* 26 * 0 turn right 27 * 1 turn down 28 * 2 turn left 29 * 3 turn up 30 */ 31 int dir = 0; 32 int count = 65; 33 while(1){ 34 array[x][y] = count; 35 36 if(0 == dir){ 37 if( ( (y+1) == N) || (array[x][y+1] != 0) ){ 38 dir = (dir+1)%4; 39 x = x + 1; 40 } 41 else{ 42 y = y + 1; 43 } 44 } 45 else if(1 == dir){ 46 if( ( (x+1) == M) || (array[x+1][y] != 0) ){ 47 dir = (dir + 1)%4; 48 y = y -1; 49 } 50 else{ 51 x = x + 1; 52 } 53 } 54 else if(2 == dir){ 55 if( ( (y-1) < 0) || (array[x][y-1] != 0) ){ 56 dir = (dir + 1)%4; 57 x = x - 1; 58 } 59 else{ 60 y = y - 1; 61 } 62 } 63 else if(3 == dir){ 64 if( ( (x-1) < 0) || (array[x-1][y] != 0) ){ 65 dir = (dir + 1)%4; 66 y = y + 1; 67 } 68 else{ 69 x = x - 1; 70 } 71 } 72 73 //break or add moveStep 74 if(count == totalStep+64) 75 break; 76 else 77 count++; 78 } 79 80 //print 81 for( i = 0; i < M; i++){ 82 for( j= 0; j < N; j++) 83 printf("%3c", array[i][j]); 84 printf(" "); 85 } 86 return 0; 87 }