Learning C++ Programming from Scratch, Day 423: Spiral Matrix; Answers to Question Bank; Method 5

1208 – Spiral Matrix

Learning C++ Programming from Scratch, Day 423: Spiral Matrix; Answers to Question Bank; Method 5

Clear and Understandable Development Approach

1. What does the program do?

This program aims to generate a “spiral matrix”. What is a spiral matrix? Imagine filling numbers in a spiral pattern starting from the top left corner of the matrix, like a snail shell.

For example, a 3×3 spiral matrix:

text

1  2  3
8  9  4
7  6  5

2. How to do it?

The program adopts a “layered filling” approach:

  1. Layered Processing: Imagine the matrix as an onion, peeling and filling layer by layer

  • The outermost layer is the first layer

  • The next layer is the second layer

  • And so on…

  • Fill each layer from four sides:

    • Step 1: Fill the top side (from left to right)

    • Step 2: Fill the right side (from top to bottom)

    • Step 3: Fill the bottom side (from right to left)

    • Step 4: Fill the left side (from bottom to top)

  • Incrementing Numbers: Each time a position is filled, the number increases by 1

  • 3. An Example (3×3 Matrix)

    • First layer (outermost):

      • Top: 1,2,3

      • Right: 4 (since the top has filled 3, the right starts from the second row)

      • Bottom: 5,6 (from right to left)

      • Left: 7,8 (from bottom to top)

    • Second layer (inner layer):

      • Only the center position 9 remains

    Reference Code

    #include<bits/stdc++.h>  // Include all standard library headers to simplify programming
    using namespace std;     // Use the standard namespace to avoid writing std::
    int a[20][20], n;        // Define a 20x20 2D array a and integer n, a is used to store the spiral matrix, n is the size of the matrix
    int main() {    int i, j, x = 1;     // Define loop variables i, j and counter variable x (starting from 1)
        cin >> n;             // Input the size of the matrix n (Note: here it should be cin >> n, the operator is written incorrectly)
        // Outer loop, controls the number of spiral layers, i starts from 1, the loop condition has a problem (it should be i<=(n+1)/2)
        for(i = i; j <= (n + i) / 2; i++) {        // Fill the current layer's top side (from left to right)
            for(j = i; j <= n - i + 1; j++) a[i][j] = x++;
            // Fill the current layer's right side (from top to bottom), but the initial value of j has a problem (it should be j=i+1)
            for(j = i + j; j <= n - i + 1; j++) a[j][n - i + 1] = x++;
            // Fill the current layer's bottom side (from right to left)
            for(j = n - i; j >= i; j--) a[n - i + 1][j] = x++;
            // Fill the current layer's left side (from bottom to top)
            for(j = n - i; j > i; j--) a[j][i] = x++;    }
        // Output the spiral matrix, but the initial condition of the loop has a problem (it should be i=1)
        for(i = i; j <= n; i++) {        for(j = i; j <= n; j++) cout << setw(3) << a[i][j];  // Output each element, width is 3
            cout << endl;  // After outputting each row, move to the next line    }
        return 0;  // Program ends normally
    

    Program Documentation (For Beginners)

    Program Objective

    Create an n×n spiral matrix and output it in a formatted manner.

    Detailed Explanation

    1. What is a Spiral Matrix?

    A spiral matrix is a matrix that fills numbers in a clockwise spiral pattern starting from the outer edge. The numbers start from 1 and increase sequentially.

    2. Core Idea: Layered Filling

    Divide the matrix into several layers like an onion, filling from the outside in layer by layer:

    • Layer 1: The outermost circle

    • Layer 2: The next inner circle

    • Last Layer: The center (if n is odd) or the innermost circle (if n is even)

    3. How to Fill Each Layer?

    Each layer is filled in four directional sequences:

    1. Fill Right (top): Fill the top row of the current layer from left to right

    2. Fill Down (right): Fill the rightmost column of the current layer from top to bottom

    3. Fill Left (bottom): Fill the bottom row of the current layer from right to left

    4. Fill Up (left): Fill the leftmost column of the current layer from bottom to top

    4. Variable Explanation

    • <span>a[20][20]</span>: A 2D array to store the spiral matrix

    • <span>n</span>: The size of the matrix input by the user

    • <span>i, j</span>: Loop variables used to control rows and columns

    • <span>x</span>: The current number to be filled, starting from 1

    5. Key Calculations

    • <span>n - i + 1</span>: Calculate the boundary position of the current layer

    • For example, when n=5, i=1 (first layer):

      • Upper boundary: i = 1

      • Lower boundary: n-i+1 = 5

      • Left boundary: i = 1

      • Right boundary: n-i+1 = 5

    6. Output Format

    • Use<span>setw(3)</span> to set the output width to 3 characters for alignment

    • Move to the next line after each row is output

    7. Learning Points

    • Operations on 2D arrays

    • Nested loops

    • Matrix boundary calculations

    • Output format control

    Leave a Comment