劍指offer——(17)順時針列印矩陣
阿新 • • 發佈:2018-12-04
學資料結構的時候有做過一道類似的題目,不一樣的是當時的二維陣列規定是正方形,而這裡是矩形,然後我就不會了。。
演算法圖示(4x3矩陣):
ac程式碼(java):
import java.util.ArrayList; public class Solution { public Solution() { int test[][] = new int[][] { { 1, 2, 3}, { 4, 5, 6 }, { 7, 8, 9}, {10, 11, 12 }}; System.out.println(printMatrix(test)); //[1, 2, 3, 6, 9, 12, 11, 10, 7, 4] } public ArrayList<Integer> printMatrix(int[][] matrix) { ArrayList<Integer> AL = new ArrayList<Integer>(); int left = 0, top = 0, right = matrix[0].length - 1, bottom = matrix.length - 1; while (left <= right && top <= bottom) { //頂部從左往右 for (int i = left; i <= right; i++) AL.add(matrix[top][i]); //右邊從上往下 for (int i = top + 1; i <= bottom; i++) AL.add(matrix[i][right]); //底部從右往左 if (top != bottom) //當二維陣列只有一行時,避免重複輸出 for (int i = right -1; i >= left; i--) AL.add(matrix[bottom][i]); //左邊從下往上 if (left != right) //當二維陣列只有一列時,避免重複輸出 for (int i = bottom -1; i > top; i--) AL.add(matrix[i][left]); left++; top++; right--; bottom--; } return AL; } /* * if (Math.sqrt(matrix.length * matrix[0].length) % 2 != 0) AL.add(matrix[(int) * (Math.sqrt(matrix.length) / 2) + 1][(int) (Math.sqrt(matrix.length) / 2) + * 1]); */ public static void main(String args[]) { new Solution(); } }