码迷,mamicode.com
首页 > 编程语言 > 详细

剑指Offer(书):顺时针打印数组

时间:2018-08-21 22:33:15      阅读:251      评论:0      收藏:0      [点我收藏+]

标签:依次   public   author   color   矩阵   lis   port   imp   arrays   

题目:输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下4 X 4矩阵: 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.gjjun.jzoffer;import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 顺时针打印矩阵
 *
 * @author gjjun
 * @date 2018/8/21
 **/
public class Solution29 {
    public static void main(String[] args) {
        int[][] arr = new int[2][4];
        int num = 1;
        for (int i = 0; i < 2; i++) {
            for (int j = 0; j < 4; j++) {
                arr[i][j] = num;
                num++;
            }
        }
        System.out.println(Arrays.deepToString(arr));
        System.out.println(Arrays.toString(print(arr).toArray()));
    }

    public static ArrayList<Integer> print(int[][] array) {
        ArrayList<Integer> list = new ArrayList<>();
        if (array == null || array.length == 0) {
            return list;
        }
        int row = array.length;
        int col = array[0].length;
        int[][] temp = new int[row][col];
        temp[0][0] = 1;
        int i = 0;
        int j = 0;
        list.add(array[i][j]);
        int min = row > col ? col : row;
        min = (min & 1) == 1 ? min / 2 + 1 : min / 2;
        while (min-- > 0) {
            while (j < col - 1 && temp[i][j + 1] == 0) {
                list.add(array[i][j + 1]);
                temp[i][j + 1] = 1;
                j++;
            }
            while (i < row - 1 && temp[i + 1][j] == 0) {
                list.add(array[i + 1][j]);
                temp[i + 1][j] = 1;
                i++;
            }
            while (j > 0 && temp[i][j - 1] == 0) {
                list.add(array[i][j - 1]);
                temp[i][j - 1] = 1;
                j--;
            }
            while (i > 0 && temp[i - 1][j] == 0) {
                list.add(array[i - 1][j]);
                temp[i - 1][j] = 1;
                i--;
            }
        }
        return list;
    }
}

 

剑指Offer(书):顺时针打印数组

标签:依次   public   author   color   矩阵   lis   port   imp   arrays   

原文地址:https://www.cnblogs.com/liter7/p/9452400.html

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