首页 > 代码库 > 打印数字回环

打印数字回环

题目要求:

Input a value n, then print out a n×n matrix.

    Example 1: Input 2, output
1 2
4 3
    Example2: Input 5, output
  1    2    3    4    5
 16   17   18   19    6
 15   24   25   20    7
 14   23   22   21    8
 13   12   11   10    9


思路:

把该输出划分为多个环,每一个环上有4根线。分别为0,1,2,3号。

最外层的环每根线上有n-1个数字,每靠内一层。线上数字少2个。

计算每一个位置(row, col)相应的环、线、线内索引。进而求出环内索引和全局索引。在该位置打印全局索引就可以。


代码例如以下:

#include <algorithm>
using namespace std;

int get_number(int row, int col, int n)
{
         int n_1 = n - 1;
         int loop1 = min(row, col);
         int loop2 = min(n_1-row, n_1-col);
         int loop = min(loop1, loop2);
         int line, index_in_line;
         if (col == loop && row != loop)
        {
                line = 3;
                index_in_line = (n_1-loop) - row;
        }
         else if (n_1-row == loop)
        {
                line = 2;
                index_in_line = (n_1-loop) - col;
        }
         else if (n_1-col == loop)
        {
                line = 1;
                index_in_line = row - loop;
        }
         else if (row == loop)
        {
                line = 0;
                index_in_line = col - loop;
        }
         int line_length = n_1 - loop * 2;
         int index_in_loop = line * line_length + index_in_line;
         int before_loop = 4 * (n_1 - loop + 1) * loop;
         return before_loop + index_in_loop + 1;
}

void print_square(int n)
{
         for(int row=0; row<n; ++row)
        {
                 for(int col=0; col<n; ++col)
                {
                         int number = get_number(row, col, n);
                        printf( "%4d ", number);
                }
                printf( "\n");
        }
}

int main () {
         for(int i=1; i<10; ++i)
        {
                print_square(i);
                printf( "\n");
        }
         return 0;
}


打印数字回环