题目描述:
给你一个 m 行 n 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。
输入:
matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出:
[1,2,3,6,9,8,7,4,5]
代码实现:
import java.util.ArrayList;
import java.util.List;
//螺旋矩阵
public class Main{public static void main(String[] args) {//案例int[][] matrix = new int[][]{{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, {11, 12, 13, 14, 15, 16, 17, 18, 19, 20}};System.out.println(spiralOrder(matrix));//[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11]}/*** 定义边界之后,顺时针遍历,不断调整边界的范围** @param matrix 输入数组* @return 输出动态数组*/public static List<Integer> spiralOrder(int[][] matrix) {List<Integer> list = new ArrayList<>();//创建集合存储元素//上边界int up = 0;//左边界int left = 0;//下边界int down = matrix.length - 1;//右边界int right = matrix[0].length - 1;//遍历while (right >= 0 && up < down && left <= right) {//防止越界//遍历上边界for (int i = left; i < right; i++) {list.add(matrix[up][i]);//行不变}//遍历右边界for (int i = up; i < down; i++) {list.add(matrix[i][right]);//列不变}//遍历下边界for (int i = right; i > left; i--) {list.add(matrix[down][i]);//行不变}//遍历左边界for (int i = down; i > up; i--) {if (left == right) {//特判:当有超过两个元素为一列时,只存入左下角元素list.add(matrix[down][left]);break;} else {list.add(matrix[i][left]);//列不变}}//四周边界缩小一个单位up++;right--;down--;left++;}//遍历up等于down的一行元素if (up == down) {for (int i = left; i <= right; i++) {list.add(matrix[up][i]);}}return list;}
}