题目传送地址: https://leetcode.cn/problems/spiral-matrix/
运行效率:
代码如下:
public static ListspiralOrder(int[][] matrix) { HashSet set = new HashSet<>(); int count = matrix.length * matrix[0].length; int direction = 0;//走的方向 0:从左往右 1:从上往下 2:从右往左 3:从下往上 List list = new ArrayList<>(); int rowIndex = 0; int colIndex = 0; while (list.size() < count) { int num = matrix[rowIndex][colIndex]; list.add(num); String coordinate = rowIndex + ":" + colIndex;//坐标 set.add(coordinate); // 校验当前坐标的下一个同方向的坐标是否越界 boolean validNextCoordinate = validNextCoordinate(direction, coordinate, set, matrix); //从左往右 if (direction == 0) { if (validNextCoordinate) { //如果没有越界,那就继续往右边移动 colIndex++; } else { //如果越界,则改变方向 direction = 1; rowIndex++; //改变方向,则下一个位置的坐标应该在当前坐标的下方 } continue; } //从上往下 if (direction == 1) { if (validNextCoordinate) { //如果没有越界,那就继续往下边移动 rowIndex++; } else { //如果越界,则改变方向 那接下来就是要往左走了 direction = 2; colIndex--; } continue; } //从右往左 if (direction == 2) { if (validNextCoordinate) { //如果没有越界,那就继续往左边移动 colIndex--; } else { //如果越界,则改变方向 那接下来就是要往上走了 direction = 3; rowIndex--; } continue; } //从下往上 if (direction == 3) { if (validNextCoordinate) { //如果没有越界,那就继续往上边移动 rowIndex--; } else { //如果越界,则改变方向 那接下来就是要往右走了 direction = 0; colIndex++; } } } return list; } public static boolean validNextCoordinate(Integer direction, String coordinate, HashSet set, int[][] matrix) { String[] split = coordinate.split(":"); //当前坐标位置 int row = Integer.parseInt(split[0]); //当前行坐标位置 int col = Integer.parseInt(split[1]); //当前列坐标位置 if (direction == 0) { //如果是从左到右 col++; //行坐标不变,列坐标右移 } if (direction == 1) { //如果是从上到下 row++; //列坐标不变,行坐标下移 } if (direction == 2) { //如果是从右往左 col--; //行坐标不变,列坐标左移 } if (direction == 3) { //如果是从下往上 row--; //列坐标不变,行坐标上移 } //首先要确保下一个位置的坐标不能超过matrix的范围吧 if (row >= matrix.length || row < 0 || col >= matrix[0].length || col < 0) { return false; } //其次下一个位置的坐标不能在set里面 String nextCoordinate = row + ":" + col; return !set.contains(nextCoordinate); }



