给定一个包含 m x n 个元素的矩阵(m 行, n 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素
package test2;
import java.util.Arrays;
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int m, n;
m = sc.nextInt();
n = sc.nextInt();
int[][] matrix = new int[m][n];
for(int i = 0; i < m; i++) {
for(int j = 0; j < n; j++) {
matrix[i][j] = sc.nextInt();
}
}
System.out.println(Arrays.toString(SpiralMatrix(matrix)));
}
public static int[] SpiralMatrix (int[][] matrix) {
int m=matrix.length,n=matrix[0].length;
int index=0;
int l = 0, r = n - 1, s = 0, x = m - 1;
int[] res = new int[m * n];
while(true){
for(int i = l; i <= r; i++) {
res[index++] = matrix[s][i];
}
if(++s > x) break;
for(int i = s; i <= x; i++) {
res[index++] = matrix[i][r];
}
if(--r<l) break;
for(int i = r; i >= l; i--) {
res[index++] = matrix[x][i];
}
if(--x < s) break;
for(int i = x; i >= s; i--) {
res[index++] = matrix[i][l];
}
if(++l > r) break;
}
return res;
}
}
|