zoukankan      html  css  js  c++  java
  • 转圈打印数组问题

    1.给定一个整形矩阵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)

    解答:

    本题主要介绍一种矩阵处理方式,该方式不仅可用于这道题,还适合很多其他的面试题,就是矩阵分圈处理。在矩阵中用左上角的tr,tc和右下角的dr,dc就可以表示一个子矩阵,比如题目中的矩阵,当(tr,tc)=(0,0),(dr,dc)=(3,3)时,表示的矩阵就是整个矩阵,那么这个子矩阵的最外层部分如下:

    1   2   3   4

    5             8

    9            12

    13 14 15 16

    如果能把这个子矩阵的外层转圈打印出来,那么在(tr,tc)=(0,0),(dr,dc)=(3,3)时,打印结果为:1 2 3 4 8 12 16 15 14 13 9 5。接下来令tr和tc加1,即(tr,tc)=(1,1),令dr,dc减1,即(dr,dc)=(2,2),此时表示的子矩阵为:

    6  7

    10 11

    在把这个矩阵打印出来,结果为:6 7 11 10。把tr,tc加1,即(tr,tc)=(2,2),令dr,dc减1,即(dr,dc)=(1,1)。发现左上角坐标跑到了右下角坐标的右方或者下方,整个过程就停止。已经打印的结果就是我们要求的结果。具体代码参考如下:

     1 public void  spiralOrderPrint(int[][] matrix)
     2 {
     3     int tr=0;
     4     int  tc=0;
     5     int dr=matrix.lenth-1;
     6     int  dc=matrix[0].length-1;
     7    whiel(tr<=dr && tc<=dc)
     8   {
     9       printEdge(matrix,tr++,tc++,dr--,dc--);
    10 
    11    }
    12 }
    13  
    14  public void   printEdge(int[][] matrix,int tr,int tc,int dr,int dc)
    15  {
    16     if(tr==dr)
    17   {
    18      for(int i=tc;i<=dc;i++)
    19          System.out.print(m[tr][i]+" ");
    20   }
    21  else if(tc==dc)
    22  {
    23     for(int i=tr;i<=dr;i++)
    24          System.out.print(m[i][tc]+" ");
    25    }
    26  }else
    27 {
    28     int curc=tc;
    29     int curr=tr;
    30     while(curc!=dc)
    31    {
    32        System.out.print(m[tr][curc]+" ");
    33        curc++;
    34     }
    35   while(curr!=dr)
    36  {
    37        System.out.print(m[curr][dc]+" ");
    38        curr++;
    39   }
    40  while(curc!=tc)
    41    {
    42        System.out.print(m[dr][curc]+" ");
    43        curc--;
    44     }
    45   while(curr!=tr)
    46  {
    47        System.out.print(m[curr][tc]+" ");
    48        curr--;
    49   }
    50 }
    View Code
  • 相关阅读:
    2017 《Java》预备作业计科1502宋奇蕊
    在 Kubernetes 上调度 GPU 资源
    ceph
    网络设备的 38 个知识点
    CF1066 ABCD
    单调队列优化动态规划
    对拍
    【关于此博客】
    使用Morphia框架操作mongodb
    通过mybatis读取数据库数据并提供rest接口访问
  • 原文地址:https://www.cnblogs.com/guanling222/p/5770357.html
Copyright © 2011-2022 走看看