码迷,mamicode.com
首页 > 其他好文 > 详细

打印数字回环

时间:2014-06-22 00:38:02      阅读:409      评论:0      收藏:0      [点我收藏+]

标签:c++   编程   algorithm   

题目要求:

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;
}


打印数字回环,布布扣,bubuko.com

打印数字回环

标签:c++   编程   algorithm   

原文地址:http://blog.csdn.net/deping_chen/article/details/32729281

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!