Luogu brush questions C++ language | P5731 Serpentine square array

Learn C++ from a baby! Record the questions in the process of Luogu C++ learning and test preparation, and record every moment.

Attached is a summary post: Luogu Brush Questions C++ Language | Summary


【Description】

Given a positive integer n not greater than 9  , output  n × n  serpentine square matrix.

Starting with 1 in the upper left corner, fill in numbers clockwise, as shown in the same example. Note that each number will occupy 3 characters, and the front is filled with spaces.

【enter】

Enter a positive integer  n , the meaning is as described in the title.

【Output】

Output a snake matrix that meets the requirements of the title.

【Input example】

4

【Example of output】

1 2 3 4 12 13 14 5 11 16 15 6 10 9 8 7

【Code Explanation】

#include <bits/stdc++.h>
using namespace std;

int main()
{
    int n, a[15][15]={0}, x=1, y=1, mark=1;
    cin >> n;
    a[x][y] = mark;
    while (mark<n*n) {
        //一直往右走
        while (a[x][y+1]==0 && y+1<=n) {
            y++; mark++;
            a[x][y] = mark;
        }
        //一直往下走
        while (a[x+1][y]==0 && x+1<=n) {
            x++; mark++;
            a[x][y] = mark;
        }
        //一直往左走
         while (a[x][y-1]==0 && y-1>=1) {
            y--; mark++;
            a[x][y] = mark;
        }
        //一直往上走
        while (a[x-1][y]==0 && x-1>=1) {
            x--; mark++;
            a[x][y] = mark;
        }
    }

    //输出矩阵
    for (int i=1; i<=n; i++) {
        for (int j=1; j<=n; j++) {
            cout << setw(3) << a[i][j];
        }
        cout << endl;
    }
    return 0;
}

【operation result】

4
  1  2  3  4
 12 13 14  5
 11 16 15  6
 10  9  8  7

Guess you like

Origin blog.csdn.net/guolianggsta/article/details/132677321