基于Visual C++2012拆解世界五百强面试题--题3

时间:2023-03-08 18:45:26

请用C语言实现 输入N,打印N*N矩阵

比如 N = 3, 打印:

1 2 3

8 9 4

7 6 5

N = 4, 打印

1   2    3   4

12  13   14  5

11  16   15  6

10  9    8   7

启动2012

基于Visual C++2012拆解世界五百强面试题--题3

输出结果

基于Visual C++2012拆解世界五百强面试题--题3

#include <stdio.h>
#include <stdlib.h> #define M 5
int arr[M][M] = { 0 }; //初始化数组全0 ,用0来判断数组是否赋有正确的值 void HuiJu(void); //矩阵赋值函数
void ShowArr(void); //输出矩阵 int main()
{
HuiJu();
ShowArr(); system("pause");
return 0;
} void ShowArr(void)
{
int i = 0;
int j = 0;
for (i = 0; i < M; i++)
{
for (j = 0; j < M; j++)
{
printf("%d\t", arr[i][j]);
}
printf("\n");
}
} void HuiJu(void)
{
int i = 0; //数组索引
int j = 0; //数组索引
int direc = 1; //方向控制
int num = 1; //给数组进行赋值的变量 while (num <= M*M)//对矩阵循环赋值
{
switch (direc)
{
case 1: //从左到右
while (arr[i][j] == 0 && j < M) //数组值为0以及索引j没有越界时进行
{
arr[i][j] = num;
num++;
j++; //i不变 j递增
}
j--; //改变索引为下一个变量的索引
i++; //改变索引为下一个变量的索引
direc = 2;//把方向从左到右改变为从上到下
break; case 2: //从上到下
while (arr[i][j] == 0 && i < M)//数组值为0以及索引i没有越界时进行
{
arr[i][j] = num;
num++;
i++; //j不变 i递增
}
i--; //改变索引为下一个变量的索引
j--; //改变索引为下一个变量的索引
direc = 3;//把方向从上到下改变为从右到左
break; case 3: //从右到左
while (arr[i][j] == 0 && j >= 0)//数组值为0以及索引j没有越界时进行
{
arr[i][j] = num;
num++;
j--; //i不变 j递减
}
j++; //改变索引为下一个变量的索引
i--; //改变索引为下一个变量的索引
direc = 4;//把方向从右到左改变为从上到上
break; case 4: //从下到上
while (arr[i][j] == 0) //从下到上只需要判断是否被正确赋值
{
arr[i][j] = num;
i--; //j不变 i递减
num++;
}
i++; //改变索引为下一个变量的索引
j++; //改变索引为下一个变量的索引
direc = 1; //把方向从下到上改变为从左到右
break;
}
}
}

基于Visual C++2012拆解世界五百强面试题--题3

源代码下载地址如下:

http://download.****.net/detail/yincheng01/6369295