题目:
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
Example 1:
Input: [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ] Output: [1,2,3,6,9,8,7,4,5]
Example 2:
Input: [ [1, 2, 3, 4], [5, 6, 7, 8], [9,10,11,12] ] Output: [1,2,3,4,8,12,11,10,9,5,6,7]
题意:
给定一个mXn的矩阵,我们需要螺旋式的读取矩阵中的数字。如下图所示:

解法:
我们可以看出,读取的方向一共有 四个,上下左右,这个时候我们可以进行一个逻辑的编写,最先开始向右读,之后向下,之后向左,再向上,再向右(循环往复),我们设立一个标识位就可以来表示方向
这里还有一个要注意的点就是,螺旋的圈在不断缩小,缩小的位置在 左->上的那个拐点,每到该拐点,螺旋往里缩小一格
代码:
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> res=new ArrayList<Integer>();
int direction=1; //1 right 2 down 3 left 4 up
int row=matrix.length;
if(row==0) return res;
int colunm=matrix[0].length;
int xindex=0,yindex=0;
int thick=0;
for(int i=0;i<row*colunm;i++){
res.add(matrix[xindex][yindex]);
if(i+1==row*colunm) break;
if(direction==1){
if(yindex+1<=colunm-thick-1){
yindex++;
}
else{
direction=2;
xindex++;
}
}
else if(direction==2){
if(xindex+1<=row-thick-1){
xindex++;
}
else{
direction=3;
yindex--;
}
}
else if(direction==3){
if(yindex-1>=0+thick){
yindex--;
}
else{
direction=4;
xindex--;
thick++;
}
}
else {
if(xindex-1>=0+thick){
xindex--;
}
else{
direction=1;
yindex++;
}
}
}
return res;
}
}
本文详细解析了一种从矩阵中螺旋式读取元素的算法。通过设定方向标识,实现向右、向下、向左、向上的循环读取,特别关注螺旋圈不断缩小的过程,确保所有元素被正确读取。
308

被折叠的 条评论
为什么被折叠?



