- // ************* Printf the Spiral Array M*N ************* //
- // ************* 2012.11.9 chen chenliang.iv@gmail.com ************* //
- #include<stdio.h>
- #define ROW 5 // 螺旋数组的行数
- #define COLUMN 5 // 螺旋数组的列数
- int element=1,Number=0; // Number:已经填入数组的元素个数
- int spiral_array[ROW][COLUMN]={0};
- int row=0,column=-1; // 当前填数组所在行列
- int Num_column=COLUMN,Num_row=ROW-1;
- void
- right_to_left() // 从左向右填数组
- {
- int i;
- for(i=0;i<Num_column;i++){
- column+=1;
- spiral_array[row][column]=element++;
- Number++;
- }
- Num_column--;
- }
- void
- left_to_right() //从右向左填数组
- {
- int i;
- for(i=0;i<Num_column;i++){
- column-=1;
- spiral_array[row][column]=element++;
- Number++;
- }
- Num_column--;
- }
- void
- up_to_down() //从上向下填数组
- {
- int j;
- for(j=0;j<Num_row;j++){
- row+=1;
- spiral_array[row][column]=element++;
- Number++;
- }
- Num_row--;
- }
- void
- down_to_up() //从下向上填数组
- {
- int j;
- for(j=0;j<Num_row;j++){
- row-=1;
- spiral_array[row][column]=element++;
- Number++;
- }
- Num_row--;
- }
- void
- set_array() // Fill the spiral array
- {
- int flag=1;
- for( ;Number<COLUMN*ROW; ){ // 已填元素个数小于数组元素个数时,继续填数组,否则,终止。
- switch(flag){
- case 1:
- right_to_left();
- flag=2;break;
- case 2:
- up_to_down();
- flag=3;break;
- case 3:
- left_to_right();
- flag=4;break;
- case 4:
- down_to_up();
- flag=1;break;
- }
- }
- }
- void
- print_array() // Printf the spiral array //
- {
- int row,column;
- for(row=0;row<ROW;row++){
- for(column=0;column<COLUMN;column++)
- printf(" %2d ",spiral_array[row][column]);
- putchar('\\n');
- }
- putchar('\\n');
- }
- int
- main()
- {
- set_array();
- print_array();
- return 0;
- }
- //该片段来自于http://www.codesnippet.cn/detail/291020136740.html
来源: http://www.codesnippet.cn/detail/291020136740.html