C++ implementation: spiral matrix example code

  • 2020-04-01 21:37:38
  • OfStack

< img border = 0 SRC = "/ / files.jb51.net/file_images/article/201303/2013317202148441.gif" >

Through observation, it is found that the subscript of the matrix has such a rule: after the increase of row a, the increase of column b, then the decrease of row c and then the decrease of column d, but the corresponding value is gradually increased. Therefore, it can be implemented in four loops, and it is important to note that the previous values are not overwritten when assigning. So select the same color part here, the code is as follows:


#include <iostream>
#include <iomanip>

using namespace std;

//Output helical matrix void Matrix() {     const int size = 10; //Matrix size     int matrix[size][size] = {0};

    int row = 0;     int col = 0;

    int start = 1; //The starting value     int temp = size;     for (int count = 0; count < size / 2; count++) //The size order matrix can draw the size over 2 circles     {         for (; col < temp - 1; col++) //A row of assignment             matrix[row][col] = start++;         for (; row < temp - 1; row++) //B assignment             matrix[row][col] = start++;         for (col = temp - 1; col > count; col--) //C assignment             matrix[row][col] = start++;         for (row = temp - 1; row > count; row--) //D assignment             matrix[row][col] = start++;

        //Go to the next lap         temp--;         row++;         start -= 1; //The minus 1 here is because you're going to add 1 when you change circles     }

    if (0 != size % 2) //If the size is odd then you're going to end up with a number that you can't walk through, so fill it in     matrix[row][col+1] = start + 1;

    //The output array     for (int i = 0; i < size; i++)     {         for (int j = 0; j < size; j++)         {             cout << setw(5) << matrix[i][j];         }         cout << endl;     } }

int main(int argc, char **argv) {     Matrix();     return 0; }


The results are as follows (odd and even) :

< img border = 0 SRC = "/ / files.jb51.net/file_images/article/201303/2013317201412176.jpg" >

< img SRC = "/ / files.jb51.net/file_images/article/201303/2013317201801777.jpg" border = 0 >  


Related articles: