输入包含多行,第一行两个整数n和m,代表矩阵的行数和列数,接下来n行,每行m个整数,代表矩阵matrix
。
输出包含一行,n*m个整数,代表顺时针转圈输出的矩阵matrix。
4 4 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10
额外空间复杂度O(1)
import java.util.Scanner;
public class Main {
public static void printMatrixBySpin(int[][] matrix) {
int tR = 0;
int tC = 0;
int dR = matrix.length - 1;
int dC = matrix[0].length - 1;
while (tR <= dR && tC <= dC) {
printEdge(matrix, tR++, tC++, dR--, dC--);
}
}
public static void printEdge(int[][] matrix, int tR, int tC, int dR, int dC) {
if (tR == dR) {
for (int i = tC; i <= dC; i++) {
System.out.print(matrix[tR][i] + " ");
}
} else if (tC == dC) {
for (int i = tR; i <= dR; i++) {
System.out.print(matrix[i][tC] + " ");
}
} else {
int curR = tR;
int curC = tC;
while (curC != dC) {
System.out.print(matrix[tR][curC++] + " ");
}
while (curR != dR) {
System.out.print(matrix[curR++][dC] + " ");
}
while (curC != tC) {
System.out.print(matrix[dR][curC--] + " ");
}
while (curR != tR) {
System.out.print(matrix[curR--][tC] + " ");
}
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
int[][] matrix = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
matrix[i][j] = sc.nextInt();
}
}
printMatrixBySpin(matrix);
}
}
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int m = scanner.nextInt();
int matrix[][] = new int[n][m];
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
matrix[i][j] = scanner.nextInt();
}
}
int startR=0,startC=0,endR=n-1,endC=m-1;
while(startR<=endR && startC<=endC){
if(startR==endR){
for(int j=startC;j<=endC;j++){
System.out.print(matrix[startR][j] + " ");
}
}else if(startC == endC){
for(int i=startR;i<=endR;i++){
System.out.print(matrix[i][startR] + " ");
}
}else{
int p=startC;
while(p<=endC){
System.out.print(matrix[startR][p] + " ");
p++;
}
p = startR+1;
while(p<=endR){
System.out.print(matrix[p][endC] + " ");
p++;
}
p = endC-1;
while(p>=startC){
System.out.print(matrix[endR][p] + " ");
p--;
}
p = endR - 1;
while(p>startR){
System.out.print(matrix[p][startC] + " ");
p--;
}
}
startR++;
startC++;
endR--;
endC--;
}
}
}