Advertisement
dimipan80

Square Spiral Matrix of Numbers

Aug 9th, 2014
249
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.73 KB | None | 0 0
  1. /* Write a program that reads from the console a positive integer number n (1 ≤ n ≤ 20)
  2.  * and prints a matrix holding the numbers from 1 to n*n in the form of square spiral. */
  3.  
  4. import java.util.Scanner;
  5.  
  6. public class _19_PrintSquareSpiralMatrixOfNumbers {
  7.  
  8.     public static void main(String[] args) {
  9.         // TODO Auto-generated method stub
  10.         Scanner scan = new Scanner(System.in);
  11.         System.out.print("Enter a whole positve number in the range [1 .. 20] for N: ");
  12.         int numN = scan.nextInt();
  13.         scan.close();
  14.  
  15.         if (numN > 0 && numN <= 20) {
  16.             int[][] matrix = new int[numN][numN];
  17.             int row = 0, col = 0;
  18.             int maxValue = numN * numN;
  19.             String direction = "right";
  20.  
  21.             for (int i = 1; i <= maxValue; i++) {
  22.                 matrix[row][col] = i;
  23.                 if (direction == "right" && (col + 1 == numN || matrix[row][col + 1] != 0)) {
  24.                     direction = "down";
  25.                 }
  26.  
  27.                 if (direction == "down") {
  28.                     if (row + 1 == numN || matrix[row + 1][col] != 0) {
  29.                         direction = "left";
  30.                     } else {
  31.                         row++;
  32.                     }
  33.                 }
  34.  
  35.                 if (direction == "left") {
  36.                     if (col == 0 || matrix[row][col - 1] != 0) {
  37.                         direction = "up";
  38.                     } else {
  39.                         col--;
  40.                     }
  41.                 }
  42.  
  43.                 if (direction == "up") {
  44.                     if (row == 0 || matrix[row - 1][col] != 0) {
  45.                         direction = "right";
  46.                     } else {
  47.                         row--;
  48.                     }
  49.                 }
  50.  
  51.                 if (direction == "right") {
  52.                     col++;
  53.                 }
  54.             }
  55.  
  56.             System.out.println("The Square Spiral Matrix of Numbers is:");
  57.             for (int rows = 0; rows < matrix.length; rows++) {
  58.                 for (int cols = 0; cols < matrix[0].length; cols++) {
  59.                     System.out.printf("%4d", matrix[rows][cols]);
  60.                 }
  61.  
  62.                 System.out.println();
  63.             }
  64.  
  65.         } else {
  66.             System.out.println("Error! - Invalid Input number!!!");
  67.         }
  68.     }
  69.  
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement