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

顺时针打印矩阵

时间:2015-06-23 11:57:31      阅读:118      评论:0      收藏:0      [点我收藏+]

标签:二维数组

技术分享
技术分享

分析:

技术分享

技术分享

特殊情况处理

技术分享

技术分享

代码:

package arrays20;

public class Demo01 {

    public static void ClockwisePrintMatrix(int[][] arrays,int columns,int rows){
        if(arrays==null || columns<=0 || rows<=0){
            return;
        }
        int start = 0;
        while(columns>start*2 && rows>start*2){
            CirclePrintMatrix(arrays,columns,rows,start);
            start++;
        }
    }

    public static void CirclePrintMatrix(int[][] arrays,int columns,int rows,int start){
        int endX = columns-1-start;
        int endY = rows-1-start;

        //从左到右打印一行
        for (int i = start; i <= endX; i++) {
            int number = arrays[start][i];
            System.out.print(number+" ");
        }

        //从上到下打印一行
        if(start<endY){
            for (int i = start+1; i <= endY; i++) {
                int number = arrays[i][endX];
                System.out.print(number+" ");
            }
        }


        //从右到左打印一行
        if (start<endX && start<endY) {
            for (int i = endX-1; i >= start; i--) {
                int number = arrays[endY][i];
                System.out.print(number+" ");
            }
        }

        //从下到上打印一行(至少三行两列)
        if (start<endX && start<endY-1) {
            for (int i = endY-1; i >= start+1; i--) {
                int number = arrays[i][start];
                System.out.print(number+" ");
            }
        }
    }

    public static void main(String[] args) {
        int[][] arrays = {
                {1,2,3,4},
                {5,6,7,8},
                {9,10,11,12},
                {13,14,15,16}
                };
        //System.out.println(arrays.length+","+arrays[0].length);
        // 列 行
        ClockwisePrintMatrix(arrays,arrays[0].length,arrays.length);
    }
}

运行结果:

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

顺时针打印矩阵

标签:二维数组

原文地址:http://blog.csdn.net/scgaliguodong123_/article/details/46603519

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