题目:输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下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; } }
原文地址:https://www.cnblogs.com/liter7/p/9452400.html
时间: 2024-10-06 00:28:57