从矩阵的第一个元素A[0][0] 开始,顺时针遍历矩阵的最外层元素,然后从A[1][1]遍历矩阵第二层元素,以此类推,直到遍历完所有的矩阵元素。将结果按遍历顺序放在数组中返回。 提示:矩阵不一定是方正
A:待遍历的矩阵 n:矩阵A的行数 m:矩阵A的列数
按螺旋状遍历矩阵的结果
A: 11,12,13,14,15 16,17,18,19,20 21,22,23,24,25 26,27,28,29,30 31,32,33,34,35 n:5, m:5
11,12,13,14,15,20,25,30,35,34,33,32,31,26,21,16,17,18,19,24,29,28,27,22,23
可以将矩阵看成由外到内的圈组成的一种结构,我们只要由外到内循环获取每一圈的元素,然后将这些元素按顺序添加到一个数组返回即可。设矩阵的行数为n,列数为m,矩阵每一圈的起点坐标为(x, y)。由题意可知,每一圈的起点坐标满足x=y,循环的条件为2*x
(1)从左到右获取一行元素;
(2)从上到下获取一列元素;
(3)从右到左获取一行元素;
(4)从下到上获取一列元素。
设置好各步的边界条件就可以获得相应的输出结果了。
import java.util.*; public class Main { public int[] solution(int[][] A,int n,int m) { if(A == null){ return null; } List<Integer> matrixList = new ArrayList<>(); int x = 0;//记录每一圈开始位置的行 int y = 0;//记录每一圈开始位置的列 //循环获取每一圈的元素 while(x * 2 < n && y * 2 < m){ matrixList.addAll(getCircleList(A, n, m, x, y)); x++; y++; } int resultLength = matrixList.size(); int[] result = new int[resultLength]; for(int i = 0; i < resultLength; i++){ result[i] = matrixList.get(i); } return result; } public List<Integer> getCircleList(int[][] A, int n, int m, int x, int y){ List<Integer> circleList = new ArrayList<>();//保存读取的每一圈的矩阵元素 for(int i = y; i <= m - y - 1; i++){ circleList.add(A[x][i]); } if(n - x - 1 > x){ for(int i = x + 1; i <= n - x - 1; i++){ circleList.add(A[i][m - y - 1]); } } if(n - x - 1 > x && m - 1 - y > y){ for(int i = m - y - 2; i >= y; i--){ circleList.add(A[n - 1 - x][i]); } } if(m - 1 - y > y && n - 1 - x > x + 1){ for(int i = n - 1 - x - 1; i >= x + 1; i--){ circleList.add(A[i][y]); } } return circleList; } }