Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
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]
.
package com.vic.leetcode.solutions;
import java.util.ArrayList;
import java.util.List;
public class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> list = new ArrayList<Integer>();
if(null==matrix||matrix.length==0)
return list;
int start = 0,columns = matrix[0].length,rows = matrix.length;
while(columns>2*start&&rows>2*start){
list.addAll(spiralPrint(matrix,columns,rows,start));
start++;
}
return list;
}
private List<Integer> spiralPrint(int[][] matrix,int columns, int rows, int start) {
List<Integer> tempList = new ArrayList<Integer>();
int endX = columns - start - 1;
int endY = rows - start - 1;
//from left to right
for(int i = start; i <= endX; i++){
tempList.add(matrix[start][i]);
}
//from top to bottom
if(endY > start){
for(int i = start + 1; i <= endY; i++){
tempList.add(matrix[i][endX]);
}
}
//from right to left
if(endX > start && endY > start){
for(int i = endX - 1; i >= start; i--){
tempList.add(matrix[endY][i]);
}
}
//from bottom to top
if(endX > start && endY > start){
for(int i = endY - 1; i > start; i--){
tempList.add(matrix[i][start]);
}
}
return tempList;
}
public static void main(String[] args) {
int[][] matrix = {{1,2,3},{4,5,6}};
Solution sl = new Solution();
sl.spiralOrder(matrix);
for(Integer n : sl.spiralOrder(matrix)){
System.out.print(n+" ");
}
}
}