The Serpentine fill number. In the nxn phalanx filled with 1,2,...,nxn, asked to fill the snake. For example, the n=4 matrix 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.
The solution to the problem of "resolution" is mainly about how to simulate the process of serpentine filling.
We give a definition of two concepts:
(1) Direction: The order of direction in the problem is "bottom-left-top-right"
(2) Wall: If the wall is encountered in the process of filling, it should change direction.
"A realization idea" NOTE: here I will n*n matrix generalized to n*m matrix, so that m=n.
#include <iostream>#defineMax_len 100using namespacestd;intA[max_len][max_len];intMain () {intN, m, x, Y, C; while(Cin >>N) {C=1; M=N; X= N-1; Y=0; for(inti =0; I < n; i++){ for(intj =0; J < M; J + +) {A[i][j]=0; }} A[y][x]= C + +; while(c <= N *m) { while(Y +1< n && A[y +1][X] = =0){//downwardA[++Y][X] = C + +; } while(X-1>=0&& A[y][x-1] ==0){//leftA[y][--x] = C + +; } while(Y-1>=0&& A[y-1][X] = =0){//UpwardA[--Y][X] = C + +; } while(x +1< n && a[y][x +1] ==0){//RightA[Y][++X] = C + +; } } for(inti =0; I < n; i++){ for(intj =0; J < M-1; J + +) {cout<< A[i][j] <<" "; } cout<< A[i][m-1] <<Endl; } } return 0;}
"Test Data"
[Introduction to algorithmic competition] Snake fill number