import java.util.ArrayList;
import java.util.List;
public class 螺旋打印二维数组 {
public static List<Integer> spiralOrder(int[][] matrix) {
if (matrix.length == 0) return new ArrayList<>();
if (matrix[0].length == 0) return new ArrayList<>();
List<Integer> result = new ArrayList<Integer>();
boolean[][] used = new boolean[matrix.length][matrix[0].length];
int[][] direction = {{0,1},{1,0},{0,-1},{-1,0}}; //右,下,左,上
int index = 0;
int i = 0;
int j = 0;
int iLength = matrix.length;
int jLength = matrix[0].length;
while (i >= 0 && j >= 0 && i < iLength && j < jLength) {
if (used[i][j]) break;
result.add(matrix[i][j]);
used[i][j] = true;
int iNext = i + direction[index][0];
int jNext = j + direction[index][1];
if (iNext < matrix.length && jNext < matrix[0].length
&& iNext >= 0 && jNext >= 0) {
//使用过
if (used[iNext][jNext]) {
//转方向
int tempIndex = (index + 1) % 4;
i = i + direction[tempIndex][0];
j = j + direction[tempIndex][1];
index = tempIndex;
if (used[i][j]) break;
//未使用
} else {
i = iNext;
j = jNext;
}
} else {
int tempIndex = (index + 1) % 4;
i = i + direction[tempIndex][0];
j = j + direction[tempIndex][1];
index = tempIndex;
}
}
return result;
}
}
螺旋打印二维数组
最新推荐文章于 2024-05-12 16:57:11 发布