1、题目名称
Spiral Matrix(螺旋输出矩阵中的元素)
2、题目地址
https://leetcode.com/problems/spiral-matrix/
3、题目内容
英文:Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
中文:给出一个m行n列的矩阵,以螺旋顺序返回矩阵中的所有元素。
例如:现有矩阵如下:
[ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ]
则输出应为 [1, 2, 3, 6, 9, 8, 7, 4, 5]
4、解题方法1
一种方法是使用四个数字分别记录上下左右四个边界的位置,不断循环收窄这些边界,最终当两个边界重叠时,结束循环。
Java代码如下:
import java.util.LinkedList;
import java.util.List;
/**
* @功能说明:LeetCode 54 - Spiral Matrix
* @开发人员:Tsybius2014
* @开发时间:2015年11月2日
*/
public class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
LinkedList<Integer> linkedList = new LinkedList<Integer>();
if (matrix == null || matrix.length == 0) {
return linkedList;
}
//左右上下四个边界
int left = 0;
int right = matrix[0].length - 1;
int top = 0;
int bottom = matrix.length - 1;
int i;
while (true) {
//上边,自左至右
for (i = left; i <= right; i++) {
linkedList.add(matrix[top][i]);
}
if (++top > bottom) {
break;
}
//右边,自上至下
for (i = top; i <= bottom; i++) {
linkedList.add(matrix[i][right]);
}
if (left > --right) {
break;
}
//下边,自右至左
for (i = right; i >= left; i--) {
linkedList.add(matrix[bottom][i]);
}
if (top > --bottom) {
break;
}
//左边,自下至上
for (i = bottom; i >= top; i--) {
linkedList.add(matrix[i][left]);
}
if (++left > right) {
break;
}
}
return linkedList;
}
}
5、解题方法2
另一种方法是预先指定好遍历四个边时的坐标增减方向,并在每次沿一个方向行进完毕后,计算出下个方向应行进的单位数。
Java代码如下:
import java.util.LinkedList;
import java.util.List;
/**
* @功能说明:LeetCode 54 - Spiral Matrix
* @开发人员:Tsybius2014
* @开发时间:2015年11月2日
*/
public class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
LinkedList<Integer> linkedList = new LinkedList<Integer>();
if (matrix == null || matrix.length == 0) {
return linkedList;
}
//行进方向
int[][] direction = new int[][] {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
//以初始点(0,0)的初始行进方向计算出的初始点前一个点的行列坐标
int x = 0;
int y = -1;
//矩阵的行数和列数
int m = matrix.length;
int n = matrix[0].length;
//counter决定了转动的具体方向
int counter = 0;
while (m > 0 && n > 0) {
int k;
//判断横向移动还是纵向移动
if (counter % 2 == 0) {
k = n;
m--;
} else {
k = m;
n--;
}
//沿一个方向进行移动
while (k-- != 0) {
x += direction[counter][0];
y += direction[counter][1];
linkedList.add(matrix[x][y]);
}
//调整方向
counter = (counter + 1) % 4;
}
return linkedList;
}
}
END
LeetCode:Spiral Matrix - 螺旋输出矩阵中的元素
原文:http://my.oschina.net/Tsybius2014/blog/525063