注意:这题虽然实现原理简单,但是非常非常容易写错。本人也调试了好一阵子,太容易写错了。
如果要求面试中徒手写出bug free的代码,除非事先很熟悉不然真的很容易写错。
输出一个N阶矩阵
比如输入1
输出
1
输入2
输出
1 2
4 3
输入 3
输出
1 2 3
8 9 4
7 6 5
代码如下
#define _CRT_SECURE_NO_WARNINGS
#include <tchar.h>
#include <windows.h>
#include <stdio.h>
#define MAX_ORDER 255
int array[MAX_ORDER][MAX_ORDER] = { 0 };
int _tmain(int argc, TCHAR* argv[], TCHAR * env[])
{
int num;
printf("Please the N order matrix of N:\n");
scanf("%d", &num);
int i = 0; // indicate x-coordinate
int j = 0; // indicate y-coordinate
int s = 1; // the value of the array element
int n = num; // the high bound for loop
int m = -1; // the low bound for loop
i = -1; // init the start point
j = -1; // init the start point
while (m < n) {
for (++i, ++j; j < n && (array[i][j] == 0); j++) {
array[i][j] = s++;
}
for (--j, ++i; i < n && (array[i][j] == 0); i++) {
array[i][j] = s++;
}
for (--i, --j; j > m && (array[i][j] == 0); j--) {
array[i][j] = s++;
}
for (++j, --i; i > m && (array[i][j] == 0); i--) {
array[i][j] = s++;
}
n--;
m++;
}
// print the structure of the N-order Matrix.
printf("The %d-order Matrix is:\n", num);
for (i = 0; i < num; i++){
for (j = 0; j < num; j++)
printf("%4d", array[i][j]);
printf("\n");
}
return 0;
}
输出结果。
2)以上题目进行变换,可以从中间旋转出来,例如
输入3
输出
9 8 7
2 1 6
3 4 5
修改后的代码。
#define _CRT_SECURE_NO_WARNINGS
#include <tchar.h>
#include <windows.h>
#include <stdio.h>
#define MAX_ORDER 255
int array[MAX_ORDER][MAX_ORDER] = { 0 };
int _tmain(int argc, TCHAR* argv[], TCHAR * env[])
{
int num;
printf("Please the N order matrix of N:\n");
scanf("%d", &num);
int i = 0; // indicate x-coordinate
int j = 0; // indicate y-coordinate
int s = num * num; // the value of the array element
int n = num; // the high bound for loop
int m = -1; // the low bound for loop
i = -1; // init the start point
j = -1; // init the start point
while (m < n) {
for (++i, ++j; j < n && (array[i][j] == 0); j++) {
array[i][j] = s--;
}
for (--j, ++i; i < n && (array[i][j] == 0); i++) {
array[i][j] = s--;
}
for (--i, --j; j > m && (array[i][j] == 0); j--) {
array[i][j] = s--;
}
for (++j, --i; i > m && (array[i][j] == 0); i--) {
array[i][j] = s--;
}
n--;
m++;
}
// print the structure of the N-order Matrix.
printf("The %d-order Matrix is:\n", num);
for (i = 0; i < num; i++){
for (j = 0; j < num; j++)
printf("%4d", array[i][j]);
printf("\n");
}
return 0;
}
扩展,在B站上看到这题的一个扩展,先将题目记录下来,后续研究。