[Introduction to algorithmic competition] Snake fill number

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.