LeetCode Spiral Matrix

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:

[
 [ 1, 2, 3 ],
 [ 4, 5, 6 ],
 [ 7, 8, 9 ]
]

You should return [1,2,3,6,9,8,7,4,5].

從外圍逐步向內輸出矩陣內的元素

注意矩陣爲空的情況

public class Solution {
    public ArrayList<Integer> spiralOrder(int[][] matrix) {
        int row = matrix.length;
		ArrayList<Integer> result = new ArrayList<Integer>();
		if(row==0)  //矩陣爲空的情況
		{
			return result;
		}
		int col = matrix[0].length; //如果矩陣爲空,matrix[0]不能訪問
		int rowstart = 0, rowend = row, colstart = 0, colend = col;
		int num = 0;
		while (num != row * col) {
			// 上行
			for (int i = colstart; i < colend; i++) {
				result.add(matrix[rowstart][i]);
				num++;
				if (num == row * col)
					return result;  //直接返回結果
			}
			rowstart++;
			// 右列
			for (int i = rowstart; i < rowend; i++) {
				result.add(matrix[i][colend - 1]);
				num++;
				if (num == row * col)
					return result;
			}
			colend--;
			// 下行
			for (int i = colend - 1; i >= colstart; i--) {
				result.add(matrix[rowend - 1][i]);
				num++;
				if (num == row * col)
					return result;
			}
			rowend--;
			// 左列
			for (int i = rowend - 1; i >= rowstart; i--) {
				result.add(matrix[i][colstart]);
				num++;
				if (num == row * col)
					return result;
			}
			colstart++;
		}
		return result;
    }
}





發佈了30 篇原創文章 · 獲贊 0 · 訪問量 8413
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章