import java.util.Scanner;
public class SpiralMatrix {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Lê as dimensões da matriz
int m = scanner.nextInt();
int n = scanner.nextInt();
int[][] matrix = new int[m][n];
// Lê os elementos da matriz
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
matrix[i][j] = scanner.nextInt();
}
}
// Imprime a matriz em ordem espiral
printSpiralOrder(matrix, m, n);
scanner.close();
}
public static void printSpiralOrder(int[][] matrix, int m, int n) {
int top = 0, bottom = m - 1;
int left = 0, right = n - 1;
while (top <= bottom && left <= right) {
// Imprime a linha superior da esquerda para a direita
for (int i = left; i <= right; i++) {
System.out.print(matrix[top][i] + " ");
}
top++;
// Imprime a coluna direita de cima para baixo
for (int i = top; i <= bottom; i++) {
System.out.print(matrix[i][right] + " ");
}
right--;
// Imprime a linha inferior da direita para a esquerda, se houver
if (top <= bottom) {
for (int i = right; i >= left; i--) {
System.out.print(matrix[bottom][i] + " ");
}
bottom--;
}
// Imprime a coluna esquerda de baixo para cima, se houver
if (left <= right) {
for (int i = bottom; i >= top; i--) {
System.out.print(matrix[i][left] + " ");
}
left++;
}
}
}
}
To embed this program on your website, copy the following code and paste it into your website's HTML: