Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package spiralmatrix;
- import java.util.Scanner;
- /*
- * @author Georgi Machkanov
- */
- public class SpiralMatrix {
- public static void main(String[] args) {
- Scanner input = new Scanner(System.in);
- System.out.print("x = ");
- int x = input.nextInt();
- System.out.print("y = ");
- int y = input.nextInt();
- System.out.println();
- int[][] arrInt = new int[y][x];
- /* Generate matrix [x,y] */
- for (int row = 0; row < y; row++)
- {
- for (int col = 0; col < x; col++)
- {
- arrInt[row][col] = x * row + col + 1;
- }
- }
- /* Print matrix [x,y] */
- for (int a = 0; a < y; a++)
- {
- for (int b = 0; b < x; b++)
- {
- System.out.format("%5d", arrInt[a][b]);
- }
- System.out.println();
- }
- System.out.println();
- /* Print matrix in spiral form */
- byte direction = 0; /*0-right, 1-down, 2-left, 3-right*/
- int row = 0, col = 0;
- int matrixIndex = 0;
- for (int k = 0; k < y; k++)
- {
- for (int c = 0; c < x; c++)
- {
- System.out.print(arrInt[row][col] + " ");
- if (direction == 0) //right
- {
- if (col + 1 + matrixIndex >= x)
- {
- direction = 1;
- row++;
- }
- else
- {
- col++;
- }
- }
- else if (direction == 1) //down
- {
- if (row + 1 + matrixIndex >= y)
- {
- direction = 2;
- col--;
- }
- else
- {
- row++;
- }
- }
- else if (direction == 2) //left
- {
- if (col - 1 - matrixIndex < 0)
- {
- direction = 3;
- row--;
- }
- else
- {
- col--;
- }
- }
- else if (direction == 3) //up
- {
- if (matrixIndex + 1 == row)
- {
- matrixIndex++;
- }
- if (row - 1 - matrixIndex < 0)
- {
- direction = 0;
- col++;
- }
- else
- {
- row--;
- }
- }
- }
- }
- System.out.println();
- System.out.println();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement