Given a matrix of m x n elements (m rows, n columns), return all elements of the Matri X 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 list<integer> spiralorder (int[][] matrix) {list<integer> res = new A Rraylist<integer> (); int m = matrix.length; if (M = = 0) return res; int n = matrix[0].length; The number of cycles is less than M/2 and N/2 for (int i = 0; i < M/2 && i < N/2; i++) {for (int j = 0; J < n-1-I *) 2; J + +) Res.add (Matrix[i][i+j]); for (int j = 0; J < m-1-I * 2; j + +) Res.add (matrix[i+j][n-i-1]); for (int j = 0; J < n-1-I * 2; j + +) Res.add (Matrix[m-i-1][n-i-1-j]); for (int j = 0; J < m-1-I * 2; j + +) Res.add (Matrix[m-i-1-j][i]); }//After the loop ends if the number of rows/columns is odd, then there is one row/column if (m% 2! = 0 && m <= N) {for (int j = 0; J < n-(M/2) * 2; J + +) Res.add (Matrix[m/2][m/2+j]); } else if (n% 2 = 0 && m > N) {for (int j = 0; J < m-(N/2)* 2; J + +) Res.add (MATRIX[N/2+J][N/2]); } return res; }}
Leetcode:spiral Matrix. Java