标签:style blog http color 2014 io
输出N阶螺旋矩阵,如N=5时
17 16 15 14 13
18 5 4 3 12
19 6 1 2 11
20 7 8 9 10
21 22 23 24 25
思路如下:
从二维数组的第(N-1,N-1)个元素开始,分别对矩阵最外层的四条边进行赋值操作,起始值是N*N,依次递减。
1 #include <stdio.h> 2 #include <string.h> 3 #include <stdlib.h> 4 #include <memory.h> 5 6 int N; 7 8 void generateSnake(int snake[N][N],int endRow,int endCell,int row,int cell,int start); 9 10 int main() { 11 12 scanf("%d",&N); 13 14 int snake[N][N]; 15 16 generateSnake(snake,0,0,N-1,N-1,N*N); 17 18 return 0; 19 20 } 21 22 void generateSnake(int snake[N][N],int endRow,int endCell,int row,int cell,int start) { 23 24 int ln = cell; 25 int col = row; 26 if(start > 1) { 27 28 while(col >= endCell) { 29 snake[ln][col] = start; 30 // printf("(%d,%d)%d--",ln,col,snake[ln][col]); 31 start--; 32 col--; 33 } 34 col = endCell; 35 ln--; 36 37 while(ln >= endRow) { 38 snake[ln][col] = start; 39 // printf("(%d,%d)%d**",ln,col,snake[ln][col]); 40 start--; 41 ln--; 42 } 43 ln = endRow; 44 45 col = endCell+1; 46 while(col <= cell) { 47 snake[ln][col] = start; 48 // printf("(%d,%d)%d^^",ln,col,snake[ln][col]); 49 start--; 50 col++; 51 } 52 col = cell; 53 ln++; 54 55 while(ln < row) { 56 snake[ln][col] = start; 57 // printf("(%d,%d)%d$$",ln,col,snake[ln][col]); 58 start--; 59 ln++; 60 } 61 ln--; 62 63 generateSnake(snake,endRow+1,endCell+1,row-1,cell-1,start); 64 65 }else { 66 snake[(N-1)/2][(N-1)/2]=1; 67 int k = 0; 68 int m; 69 while(k < N) { 70 m=0; 71 for(;m < N;m++) { 72 printf("%2d ",snake[k][m]); 73 } 74 if(m==N) 75 printf("\n"); 76 k++; 77 } 78 k = 0; 79 m = N-1; 80 int temp = 0; 81 while(k < N) { 82 temp = temp + snake[k][k]+snake[m][k]; 83 m--; 84 k++; 85 } 86 printf("%2d ",temp-1); 87 } 88 }
输入:
7
输出:
标签:style blog http color 2014 io
原文地址:http://www.cnblogs.com/nora-xie/p/3856504.html