原创内容,如需转载,请注明出处
题目大意:输入一个正数n,按顺时针方向打印n * n的蛇型矩阵。
输入:
6
输出:
1 2 3 4 5 6
20 21 22 23 24 7
19 32 33 34 25 8
18 31 36 35 26 9
17 30 29 28 27 10
16 15 14 13 12 11
代码如下
1 #include <stdio.h> 2 #include <stdlib.h> 3 4 void snakeArr(int **arr,int n) 5 { 6 int val,i,j,left,right,low,high; 7 8 left = low = 0; 9 right = high = n -1; 10 val = 0; 11 while(left <= right && low <= high){ 12 for(i = left; i <= right; i++){ 13 arr[low][i] = ++val; 14 } 15 for(i = low + 1; i <= high; i++){ 16 arr[i][right] = ++val; 17 } 18 for(i = right - 1; i >= left; i--){ 19 arr[high][i] = ++val; 20 } 21 for(i = high - 1; i > low; i--){ 22 arr[i][left] = ++val; 23 } 24 25 low++;left++;high--;right--; 26 } 27 printf("蛇型矩阵 "); 28 for(i = 0; i < n; i++){ 29 for(j = 0; j < n; j++) 30 printf("%5d ",arr[i][j]); 31 printf(" "); 32 } 33 } 34 int main() 35 { 36 int **arr,i,n; 37 scanf("%d",&n); 38 arr = (int **)malloc(sizeof(int) * n); 39 for(i = 0; i < n; i++) 40 arr[i] = (int *)malloc(sizeof(int) * n); 41 snakeArr(arr,n); 42 system("pause"); 43 return 0; 44 }