Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* Write a program that reads from the console a positive integer number n (1 ≤ n ≤ 20)
- * and prints a matrix holding the numbers from 1 to n*n in the form of square spiral. */
- import java.util.Scanner;
- public class _19_PrintSquareSpiralMatrixOfNumbers {
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- Scanner scan = new Scanner(System.in);
- System.out.print("Enter a whole positve number in the range [1 .. 20] for N: ");
- int numN = scan.nextInt();
- scan.close();
- if (numN > 0 && numN <= 20) {
- int[][] matrix = new int[numN][numN];
- int row = 0, col = 0;
- int maxValue = numN * numN;
- String direction = "right";
- for (int i = 1; i <= maxValue; i++) {
- matrix[row][col] = i;
- if (direction == "right" && (col + 1 == numN || matrix[row][col + 1] != 0)) {
- direction = "down";
- }
- if (direction == "down") {
- if (row + 1 == numN || matrix[row + 1][col] != 0) {
- direction = "left";
- } else {
- row++;
- }
- }
- if (direction == "left") {
- if (col == 0 || matrix[row][col - 1] != 0) {
- direction = "up";
- } else {
- col--;
- }
- }
- if (direction == "up") {
- if (row == 0 || matrix[row - 1][col] != 0) {
- direction = "right";
- } else {
- row--;
- }
- }
- if (direction == "right") {
- col++;
- }
- }
- System.out.println("The Square Spiral Matrix of Numbers is:");
- for (int rows = 0; rows < matrix.length; rows++) {
- for (int cols = 0; cols < matrix[0].length; cols++) {
- System.out.printf("%4d", matrix[rows][cols]);
- }
- System.out.println();
- }
- } else {
- System.out.println("Error! - Invalid Input number!!!");
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement