题目描述
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下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.
我的解答
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
|
import java.util.ArrayList; public class Solution { private class Bounds{ int left, top, right, bottom; } public ArrayList<Integer> printMatrix(int [][] matrix) { ArrayList<Integer> result = new ArrayList(); if (null == matrix || matrix.length == 0) { return result; } else { //init Bounds bounds = new Bounds(); bounds.left = bounds.top = 0; bounds.bottom = matrix.length - 1; bounds.right = matrix[0].length - 1; while (bounds.left <= bounds.right || bounds.top <= bounds.bottom) { if(visitTop(matrix, bounds, result)) break; if (visitRight(matrix, bounds, result)) break; if (visitBottom(matrix, bounds, result)) break; if (visitLeft(matrix, bounds, result)) break; } return result; } } /** * 按顺序定义顺时针访问的四个方法 **/ private boolean visitTop(int [][] matrix, Bounds bounds, ArrayList<Integer> result) { for (int i = bounds.left; i <= bounds.right; i++) { result.add(new Integer(matrix[bounds.top][i])); } bounds.top++; return bounds.top > bounds.bottom; } private boolean visitRight(int [][] matrix, Bounds bounds, ArrayList<Integer> result) { for (int i = bounds.top; i <= bounds.bottom; i++) { result.add(new Integer(matrix[i][bounds.right])); } bounds.right--; return bounds.left > bounds.right; } private boolean visitBottom(int [][] matrix, Bounds bounds, ArrayList<Integer> result) { for (int i = bounds.right; i >= bounds.left; i--) { result.add(new Integer(matrix[bounds.bottom][i])); } bounds.bottom--; return bounds.top > bounds.bottom; } private boolean visitLeft(int [][] matrix, Bounds bounds, ArrayList<Integer> result) { for (int i = bounds.bottom; i >= bounds.top; i--) { result.add(new Integer(matrix[i][bounds.left])); } bounds.left++; return bounds.left > bounds.right; } }
|
近期评论