import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Ler m e n
System.out.print("Digite o número de linhas (m): ");
int m = sc.nextInt();
System.out.print("Digite o número de colunas (n): ");
int n = sc.nextInt();
// Ler a matriz de m por n
int[][] matriz = new int[m][n];
System.out.println("Digite a matriz:");
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
matriz[i][j] = sc.nextInt();
}
}
// Variáveis para os limites da espiral
int top = 0;
int bottom = m - 1;
int left = 0;
int right = n - 1;
// StringBuilder para construir a saída
StringBuilder result = new StringBuilder();
// Percorrer a matriz em ordem espiral
while (top <= bottom && left <= right) {
// Percorrer da esquerda para a direita na linha superior
for (int j = left; j <= right; j++) {
result.append(matriz[top][j]).append(" ");
}
top++;
// Percorrer de cima para baixo na coluna da direita
for (int i = top; i <= bottom; i++) {
result.append(matriz[i][right]).append(" ");
}
right--;
if (top <= bottom) {
// Percorrer da direita para a esquerda na linha inferior
for (int j = right; j >= left; j--) {
result.append(matriz[bottom][j]).append(" ");
}
bottom--;
}
if (left <= right) {
// Percorrer de baixo para cima na coluna da esquerda
for (int i = bottom; i >= top; i--) {
result.append(matriz[i][left]).append(" ");
}
left++;
}
}
// Imprimir o resultado
System.out.println(result.toString().trim());
sc.close();
}
}
To embed this program on your website, copy the following code and paste it into your website's HTML: