52. 铺地板

时间: 2023-09-30 admin IT培训

52. 铺地板

52. 铺地板

背景:

    你是一名室内装潢工程队的配料员。你的伙伴们喜欢采用“之”字型的方式铺大理石地砖,图案如下:

126715
3581416
49131722
1012182123
1119202425

学了 C 语言以后,你决定编写一个程序,帮助你的同伴生成这样的图形。

输入:

    方阵N的大小。

输出

    方阵。

#include "stdio.h"#define MAX 100int main(int argc, char **argv)
{int n , arr[MAX][MAX];scanf("%d", &n);getchar();int num = 1;		//自增的数字int state = 0;		//状态,对应数字递增的方向int i = 1, j = 1;if(1==n){printf(" 1\n");return 0;}if(0==n%2){while (1){//上三角arr[i][j] = num++;if (i == 1 || j == 1){state = (state + 1) % 4;}//碰到边缘,改变状态,变成下一下一种状态,即下一种方向if (i == 1 && j == n){break;}	//上半部分完毕		                 switch (state){ case 0:i--;j++;break;       //右上			                            			case 1:j++;break;           //向右			                        			case 2:i++;j--;break;       //左下			                         			case 3:i++;break;           //向下}}	state = 0;i = 2;j = n - 1;//下三角部分while (1){arr[i][j] = num++;if (i == n || j == n){state = (state + 1) % 4;}//碰到边缘,改变状态,变成下一下一种状态,即下一种方向if (i == n && j == n){break;}switch (state){case 2:i--;j++;break;//右上case 1:j++;break; //向右case 0:i++;j--;break;//左下case 3:i++;break;//向下}}}else{//上三角部分while (1){arr[i][j] = num++;if (i == 1 || j == 1)           //碰到边缘,改变状态state = (state + 1) % 4;    //变成下一下一种状态,即下一种方向if (i == 1 && j == n)break;switch (state){case 0:       //右上i--;j++;break;case 1:       //向右j++;break;case 2:       //左下i++;j--;break;case 3:       //向下i++;break;}	}state = 0;i = 2;	j = n;//下三角部分while (1){arr[i][j] = num++;if (i == n || j == n)			//碰到边缘,改变状态state = (state + 1) % 4;    //变成下一下一种状态,即下一种方向if (i == n && j == n)break;switch (state){case 3:       //右上i--;j++;break;case 2:       //向右j++;break;case 1:       //左下i++;j--;break;case 0:       //向下i++;break;}	}}//输出for (i = 1; i <= n; i++){for (j = 1; j <= n; j++){if (j != n)printf("%2d ", arr[i][j]);elseprintf("%2d", arr[i][j]);}printf("\n");}return 0;
}