In the n*n phalanx filled with,?, n*n, asked to fill the snake. For example n=4 when the Phalanx is
10 11 12 1
9 16 13 2
8 15 14 3
7 6 5 4
Above the square, the extra space is only to facilitate the observation of the law, do not have to strictly output. N≤8.
#include <stdio.h> #include <stdlib.h> #include <string.h> #define MAXN 10int A[maxn][maxn];int Main ( int argc, char *argv[]) {int n, count = 1; int x, y; scanf ("%d", &n); memset (A, 0, sizeof (a)); x = 0; y = n-1; A[x][y] = 1; while (Count < N*n) {while (X+1<n &&!a[x+1][y]) a[++x][y] = ++count;//a[x++][y] Details determine success or failure, so that x changes the W Hile (y-1>=0 &&!a[x][y-1]) a[x][--y] = ++count; while (x-1>=0 &&!a[x-1][y]) a[--x][y] = ++count; while (Y+1<n &&!a[x][y+1]) a[x][++y] = ++count; } for (x = 0; x < n; + +) {for (y = 0; y < n; y++) printf ("%3d", A[x][y]); printf ("\ n"); }/* while (Count <= n*n) {while (x < n-1 &&!a[x][y]) {A[x][y] = count; x + +; count++;} while (Y > 0 &&!a[x][y]) {A[x][y] = count; y--; count++;} while (x > 0 &&!a[x][y]) {A[x][y] = count; x--; count++;} while (Y < n-1 &&!a[x][y]) {A[x][y] = CounT y++; count++; }} for (x = 0; <= n-1; x + +) {for (y = 0; y< n-1; y++) printf ("%d", a[x][y]); printf ("%d\n", A[x][y]); } */System ("PAUSE"); return 0;}
Summary: 1 Determine whether to cross the border and determine whether to fill in the numbers
2 boundary conditions,> or >= etc., first judgment, after X, y changes
3 x + + also changes, keep in mind
4 A[0][3] It was assigned at the beginning.
Algorithmic competition Getting Started classic example 3-2 snake fill number