题目要求:
用C编写程序并注释
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
编写当N时的输出
代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
enum {
MASK_UP = 1,
MASK_DOWN = 2,
MASK_LEFT = 4,
MASK_RIGHT = 8,
TURN_NONE = 0,
TURN_UP = 1,
TURN_DOWN = 2,
TURN_LEFT = 3,
TURN_RIGHT = 4,
};
int directs[5][2] = {
{0, 0}, // 0:TURN_NONE
{-1, 0}, // 1:TURN_UP
{1, 0}, // 2:TURN_DOWN
{0, -1}, // 3:TURN_LEFT
{0, 1}, // 4:TURN_RIGHT
};
int rules[16] = {
TURN_NONE, // 0:none
TURN_UP, // 1:up
TURN_DOWN, // 2:down
TURN_NONE, // 3:invalid
TURN_LEFT, // 4:left
TURN_LEFT, // 5:left and up
TURN_DOWN, // 6:left and down
TURN_NONE, // 7:invalid
TURN_RIGHT, // 8:right
TURN_UP, // 9:right and up
TURN_RIGHT, // 10:right and down
TURN_NONE, // 11-15:invalid
};
int next_pos(int *matrix, int n, int i, int j, int *nexti, int *nextj)
{
if (i == -1 || j == -1)
{
*nexti = 0;
*nextj = 0;
return 1;
}
int mask = 0;
if (i - 1 >= 0 && matrix[(i - 1) * n + j] == 0) // up ok
mask |= MASK_UP;
if (i + 1 <= n - 1 && matrix[(i + 1) * n + j] == 0) // down ok
mask |= MASK_DOWN;
if (j - 1 >= 0 && matrix[i * n + (j - 1)] == 0) // left ok
mask |= MASK_LEFT;
if (j + 1 <= n - 1 && matrix[i * n + (j + 1)] == 0) // right ok
mask |= MASK_RIGHT;
int rule = rules[mask];
int *direct = directs[rule];
if (direct[0] == 0 && direct[1] == 0)
return 0;
*nexti = i + direct[0];
*nextj = j + direct[1];
return 1;
}
int main(int argc, char *argv[])
{
if (argc != 2)
return -1;
int n = atoi(argv[1]);
if (n <= 0)
return -1;
int *matrix = (int*)malloc(n * n * sizeof(int));
memset(matrix, 0, n * n * sizeof(int));
int i = -1;
int j = -1;
int value = 1;
while (next_pos(matrix, n, i, j, &i, &j) != 0)
{
matrix[i * n + j] = value++;
}
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
{
printf("%d", matrix[i * n + j]);
if (j != n - 1)
printf("\t");
}
printf("\n");
}
free(matrix);
return 0;
}