题目描述如下:
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:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
You should return [1,2,3,6,9,8,7,4,5].
一道简单的模拟题,主要的思路有那么几个:
1、定义一个标志行进方向的变量direction,取值范围为[0,3],分别代表四个方向;
2、定义两个数组directionX[],directionY[],组合使用表示下一个的位置;
3、定义一个标记数组flagArray[],对经过的位置进行标志;
4、定义两个变量currentX ,currentY代表当前所在的位置;
5、判断调转方向的时机(5个条件,具体见代码),并修改行进方向的变量direction。
具体实现:
public class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> resList = new ArrayList<Integer>();
int widtn = matrix.length;
if(widtn == 0) return resList;
int len = matrix[0].length;
int [][]flagArray = new int[widtn][len];
int direction = 0; // 初始方向
int currentX = 0, currentY = 0;
int []directionY = {1, 0, -1, 0};
int []directionX = {0, 1, 0, -1};
int count = len * widtn;
while(count > 0){
int value = matrix[currentX][currentY];
resList.add(value);
flagArray[currentX][currentY] = 1;
if(currentX + directionX[direction] < widtn &&
currentX + directionX[direction] >= 0 &&
currentY + directionY[direction] < len &&
currentY + directionY[direction] >= 0 &&
flagArray[currentX + directionX[direction]][currentY + directionY[direction]] != 1){
currentX = currentX + directionX[direction];
currentY = currentY + directionY[direction];
}else{
direction = (++ direction) % 4;
currentX = currentX + directionX[direction];
currentY = currentY + directionY[direction];
}
count --;
}
return resList;
}
}
题目链接:https://leetcode.com/problems/spiral-matrix/