Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner;
- public class SpiralMatrix {
- public static void main(String[] args) {
- Scanner sc = new Scanner(System.in);
- int n = sc.nextInt();
- int[][] matrix = new int[n][n];
- int num = 1;
- int row = 0;
- int col = 0;
- while (num <= n * n) {
- // GO RIGHT
- for (; col < n; col++) {
- if (matrix[row][col] == 0) {
- matrix[row][col] = num++;
- } else {
- col--;
- break;
- }
- }
- // GO DOWN
- if (col >= n) {
- col--;
- }
- if (col < 0) {
- col = 0;
- }
- row++;
- for (; row < n; row++) {
- if (matrix[row][col] == 0) {
- matrix[row][col] = num++;
- } else {
- row--;
- break;
- }
- }
- // GO LEFT
- if (row < 0) {
- row = 0;
- }
- if (row >= n) {
- row--;
- }
- col--;
- for (; col >= 0; col--) {
- if (matrix[row][col] == 0) {
- matrix[row][col] = num++;
- } else {
- col++;
- break;
- }
- }
- // GO UP
- if (col < 0) {
- col = 0;
- }
- row--;
- if (row < 0) {
- row = 0;
- }
- for (; row >= 0; row--) {
- if (matrix[row][col] == 0) {
- matrix[row][col] = num++;
- } else {
- row++;
- break;
- }
- }
- col++;
- if (col >= n) {
- col--;
- }
- if (row >= n) {
- row--;
- }
- }
- // PRINT MATRIX
- for (int i = 0; i < matrix.length; i++) {
- for (int j = 0; j < matrix[i].length; j++) {
- System.out.print(matrix[i][j]);
- if (matrix[i][j] < 10) {
- System.out.print(" ");
- } else {
- System.out.print(" ");
- }
- }
- System.out.println();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement