前言新年第一篇部落格先來一個解題報告吧,主要也是自己比較懶,跨年夜女友發燒各種照顧了,沒來得及寫年終總結,這篇解題報告也是我在做題過程中有些心得體會,跟大家分享!
在這裡,先祝福各位看我部落格的同學元旦快樂,萬事如意
題目Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
For example,
Given the following matrix:
You should return [1,2,3,6,9,8,7,4,5].
思路其實就是按照從(上->右->下->左)的順序解析矩陣,同時考慮只有一行或者只有一列的情況,切忌心浮氣躁
AC代碼
public class Solution { public ArrayList<Integer> spiralOrder(int[][] matrix) { int minX, minY, maxX, maxY, x, y; ArrayList<Integer> list = new ArrayList<Integer>(); // special case if (matrix == null || matrix.length == 0) { return list; } // initial variable minX = minY = 0; maxX = matrix.length - 1; maxY = matrix[0].length - 1; for (; minX <= maxX && minY <= maxY; minX++, minY++, maxX--, maxY--) { x = minX; y = minY; list.add(matrix[x][y]); // only a row if (minX == maxX) { for (y += 1; y <= maxY; y++) { list.add(matrix[x][y]); } break; } // only a column if (minY == maxY) { for (x += 1; x <= maxX; x++) { list.add(matrix[x][y]); } break; } // a square for (y += 1; y <= maxY; y++) { // top list.add(matrix[x][y]); if (y == maxY) break; } for (x += 1; x <= maxX; x++) { // right list.add(matrix[x][y]); if (x == maxX) break; } for (y -= 1; y >= minY; y--) { // bottom list.add(matrix[x][y]); if (y == minY) break; } for (x -= 1; x > minX; x--) { // left list.add(matrix[x][y]); if (x == minX + 1) break; } } return list; }}