【剑指offer】顺时针打印数组

顺时针打印数组

题意

例如我们有一个二维数组,如下

  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

思路

设置四个下标,分别代表左上、右上、右下、左下的下标,每次首先从左上遍历到右上,再从右上到右下,接着从右下到左下,再从左下到左上,此时更新这四个下标的值。

值得注意的是当从右下到左下和左下到左上的时候,要注意左右下标和上下下标是否已经相遇了,如果已经相遇就无需再遍历了。

代码

package com.niuke;

import java.util.ArrayList;

/**
 * Created by puyangsky on 17/3/11.
 * 顺时针打印数组
 *  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
 */
public class PrintMatrix {
    public static ArrayList<Integer> printMatrix(int [][] matrix) {
        int h = matrix.length;
        int l = matrix[0].length;
        ArrayList<Integer> ans = new ArrayList<Integer>();
        if (h==0 || l==0) return ans;
        int left_right = 0;
        int top_down = 0;
        int right_left = l-1;
        int down_top = h-1;
        while (left_right <= right_left && top_down <= down_top) {
            //从左至右打印
            for (int i = left_right; i <= right_left; i++) ans.add(matrix[top_down][i]);

            //从上至下打印
            for (int i = top_down+1; i <= down_top; i++) ans.add(matrix[i][right_left]);

            //从右至左打印
            if(top_down < down_top) {
                for (int i = right_left-1; i >= left_right; i--) ans.add(matrix[down_top][i]);
            }

            //从下至上打印
            if(right_left > left_right) {
                for (int i = down_top-1; i >= top_down+1; i--) ans.add(matrix[i][left_right]);
            }
            //更新四个下标的值
            down_top--;left_right++;right_left--;top_down++;
        }

        return ans;
    }

    public static void main(String[] args) {
        int[][] matrix = {
                {1,2},
                {3,4},
                {5,6},
                {7,8},
                {9,10}
        };

        ArrayList<Integer> ans = new ArrayList<Integer>();

        ans = printMatrix(matrix);

        for(int i : ans)
            System.out.printf("%d\t", i);
    }
}

结果

1 2 4 6 8 10 9 7 5 3

posted @ 2017-03-11 17:47  puyangsky  阅读(326)  评论(0)    收藏  举报