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:
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].
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package leetcode; | |
import java.util.ArrayList; | |
/** | |
* Solution: handle it layer by layer from outer to inner. | |
* The most important is find the how to find the loop condition. Use level(every layer) here. | |
* Every level(layer) costs two rows and two cols. So level * 2 < rows && level * 2 < cols is the condition. | |
* | |
* We don't if it's a square or rectangle. So just compare rows and cols together. | |
* Or we could just need to compare Math.min(rows, cols) | |
* | |
* left -- cols-level-2 current level should be counted. cols-(level+1)-1 | |
* up -- current level counted in, so starts from rows-(level+1)-1, ends in i >= level+1 | |
* | |
* Feature(make it easy to review): | |
* down matrix[i][cols - level - 1] -- up matrix[i][level] --> cols-level-1 + level = cols - 1 | |
* right matrix[level][i] --- left matrix[rows - level - 1][i] --> level + rows-level-1 = rows -1 | |
* | |
* @author jeffwan | |
* @date Apr 2, 2014 | |
*/ | |
public class SpiralOrder { | |
public ArrayList<Integer> spiralOrder(int[][] matrix) { | |
ArrayList<Integer> result = new ArrayList<Integer>(); | |
if (matrix == null || matrix.length == 0) { | |
return result; | |
} | |
int rows = matrix.length; | |
int cols = matrix[0].length; | |
int levelNum = Math.min(rows, cols); | |
int level = 0; | |
while (level * 2 < levelNum) { | |
for (int i = level; i < cols - level; i++) { | |
result.add(matrix[level][i]); | |
} | |
for (int i = level + 1; i < rows - level; i++) { | |
result.add(matrix[i][cols - level - 1]); | |
} | |
// if only one row /col remains | |
if (rows - 2 * level == 1 || cols - 2 * level == 1) { | |
break; | |
} | |
for (int i = cols - level - 2; i >= level; i--) { | |
result.add(matrix[rows - level - 1][i]); | |
} | |
for (int i = rows - level - 2; i >= level + 1; i--) { | |
result.add(matrix[i][level]); | |
} | |
level++; | |
} | |
return result; | |
} | |
} |
No comments:
Post a Comment