zoukankan      html  css  js  c++  java
  • 转圈打印矩阵

    Problem:
      【题目】 给定一个整型矩阵matrix,请按照转圈的方式打印它。
      例如: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 打印结果为:1,2,3,4,8,12,16,15,14,13,9,5,6,7,11, 10
      【要求】 额外空间复杂度为O(1)。

    Solution:
      采用一圈一圈打印的方式,即确定左上角与右下角,然后从外向内打印一圈,打印完了之后,
      左上角向右下一一个,右下角向上上移一个,继续打印
      左上角的行>右下角的行或者左上角的列 > 右下角的列, 则打印完毕

    Code:

      

     1 #include <iostream>
     2 #include <queue>
     3 
     4 using namespace std;
     5 
     6 
     7 template<class T>
     8 void RotatePrint(T arr, const int x, const int y)
     9 {
    10     int lx = 0, ly = 0; //左上角坐标
    11     int rx = x - 1, ry = y - 1;//右下角的坐标
    12 
    13     while (lx <= rx || ly <= ry)
    14     {
    15         if (lx == rx)
    16         {
    17             for (int i = ly; i <= ry; ++i)//打印一行的矩阵
    18                 cout << arr[lx][i] << "  ";
    19         }
    20         else if (ly == ry)
    21         {
    22             for (int i = lx; i <= rx; ++i)//打印一列的矩阵
    23                 cout << arr[i][ly] << "  ";
    24         }
    25         else 
    26         {  //打印不是单行或单列的矩阵
    27 
    28             for (int i = ly; i < ry; ++i)//打印上行
    29                 cout << arr[lx][i] << "  ";
    30             for (int i = lx; i < rx; ++i)//打印右列
    31                 cout << arr[i][ry] << "  ";
    32             for (int i = ry; i > ly; --i)//打印下行
    33                 cout << arr[rx][i] << "  ";
    34             for (int i = rx; i > lx; --i)//打印左列
    35                 cout << arr[i][ly] << "  ";
    36         }
    37 
    38         lx += 1;//左上角右下移
    39         ly += 1;
    40         rx -= 1;//右下角左上移
    41         ry -= 1;
    42     }
    43     cout << endl << "******************************" << endl;
    44 
    45 }
    46 
    47 
    48 void Test()
    49 {
    50     int aa[3][3] = { 1,2,3, 4,5,6, 7,8,9 };
    51     int bb[3][4] = { 1,2,3,4,5,6,7,8,9,10,11,12 };
    52 
    53     RotatePrint(aa, 3, 3);
    54     RotatePrint(bb, 3, 4);
    55 
    56 }
  • 相关阅读:
    how to pass a Javabean to server In Model2 architecture.
    What is the Web Appliation Archive, abbreviation is "WAR"
    Understaning Javascript OO
    Genetic Fraud
    poj 3211 Washing Clothes
    poj 2385 Apple Catching
    Magic Star
    关于memset的用法几点
    c++ 函数
    zoj 2972 Hurdles of 110m
  • 原文地址:https://www.cnblogs.com/zzw1024/p/10988648.html
Copyright © 2011-2022 走看看