首页 > 技术文章 > 打印蛇形矩阵

guozhenqiang 2016-05-11 17:02 原文

问题描述:给定一个整数矩阵,将该整数矩阵顺时针打印出来,

            例如矩阵为    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

分析:这道题其实没有涉及到复杂的算法和数据结构问题,也没有简单的方法来做,只能画图找出每次循环的边界来控制,

        通过画图可以看出圈开始的第一元素可以作为我们的基准元素,确定了这个元素也就好办了。可以得出规律,每次的

        基准元素位置都是上一个基准元素的位置两个下标均加上1,即可,循环的执行条件就是要求行数和列数都大于基准

        元素下标的两倍。

        具体的Java代码如下,写法比较通用,读者可以很容易转换为其他语言实现。

 1 public class Main {
 2     public static void orderprint(int a[][]){
 3         if(a==null){
 4             System.out.println("数组不存在");
 5             return ;
 6         }
 7         int row=a.length,column=a[0].length;
 8         if(row==0 || column==0){
 9             System.out.println("数组为空数组");
10             return ;
11         }
12         int startx=0,starty=0,endx,endy;
13         int i,j;
14         while(row>starty*2 && column>startx*2)
15         {   
16             endx=column-1-startx;                      //计算出每圈的列边界
17             endy=row-1-starty;                         //计算出每圈的行边界
18             for(j=startx;j<=endx;j++)                  //上部从左到右打印
19                 System.out.print(a[starty][j]+",");
20             for(i=starty+1;i<=endy;i++)                //右部从上到下打印
21                 System.out.print(a[i][endx]+",");
22             for(j=endx-1;j>=startx;j--)                //下部从右到左打印
23                 System.out.print(a[endy][j]+",");
24             for(i=endy-1;i>starty;i--)                 //左部从下到上打印
25                 System.out.print(a[i][startx]+",");
26             startx++;starty++;                         //改变每圈第一数的位置
27         }
28     }
29     public static void main(String[] args) {
30         // TODO 自动生成的方法存根
31       int a[][]={{1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,16}};
32       orderprint(a);
33     }
34 
35 }

输出结果为:

1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10,

推荐阅读