跳转至

一本通-例5.13 蛇形填数

在n*n 的方阵里蛇形填数,比如n=4

10  11  12   1 
  9  16  13   2 
  8  15  14   3 
  7   6   5   4
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int n;
int matrix[100][100];
bool used[100][100];

void init()
{
    for (int i = 0; i < 100; ++i)
        memset(used[i], false, sizeof(used[i]));
}

void spiralMatrix(int row, int col)
{
    init();

    int cnt = 0;
    int direction = 1;
    while (cnt < n * n) {
        ++cnt;
        used[row][col] = true;
        matrix[row][col] = cnt;
        while (cnt < n * n) {
            if (direction == 0) {
                if (col + 1 < n && !used[row][col + 1]) {
                    ++col; break;
                }
                else {
                    direction = (direction + 1) % 4;
                }
            }
            if (direction == 1) {
                if (row + 1 < n && !used[row + 1][col]) {
                    ++row; break;
                }
                else {
                    direction = (direction + 1) % 4;
                }
            }
            if (direction == 2) {
                if (col - 1 >= 0 && !used[row][col - 1]) {
                    --col; break;
                }
                else {
                    direction = (direction + 1) % 4;
                }
            }
            if (direction == 3) {
                if (row - 1 >= 0 && !used[row - 1][col]) {
                    --row; break;
                }
                else {
                    direction = (direction + 1) % 4;
                }
            }
        }
    }

    for (int i = 0; i < n; ++i) {
        for (int j = 0; j < n; ++j) {
            printf("%3d ", matrix[i][j]);
        }
        printf("\n");
    }
}

int main()
{
    // std::ios_base::sync_with_stdio(false);
    // cin.tie(NULL);
    // cout.tie(NULL);

    scanf("%d", &n);
    spiralMatrix(0, n - 1);

    return 0;
}

注意memset在头文件<string.h>里面