Saturday, May 3, 2025

Spiral Display of 2D Array




package jan22;

import java.util.Scanner;

public class SpiralDisplay {

public static void main(String[] args) {

// Declare a 2D array with 3 rows and 4 columns
// Space Complexity: O(m * n), where m = 3, n = 4
int[][] arr = new int[3][4];

Scanner scanner = new Scanner(System.in); // Constant space (O(1)) for Scanner object

// Input loop to fill the 2D array
// Time Complexity: O(m * n), every element is read once
for (int i = 0; i < arr.length; i++) { // Loop over m rows
for (int j = 0; j < arr[0].length; j++) { // Loop over n columns
arr[i][j] = scanner.nextInt(); // Input each element (O(1))
}
}

spiralDisplay(arr); // Call method to print in diagonal wave order
}

private static void spiralDisplay(int[][] arr) {

int column = 0;

// First phase: traverse from top row diagonally down-right
// Total iterations: m diagonals from first column
for (int row = 0; row < arr.length; row++) {
int tempRow = row, tempCol = column;
while (tempRow >= 0 && tempCol < arr[0].length) { // Stay within bounds
System.out.print(arr[tempRow--][tempCol++] + " "); // Diagonal up-left
}
}

int row = arr.length - 1;

// Second phase: traverse from top row's second column to end, diagonally
for (int col = 1; col < arr[0].length; col++) {
int tempRow = row, tempCol = col;
while (tempCol < arr[0].length && tempRow >= 0) { // Stay within bounds
System.out.print(arr[tempRow--][tempCol++] + " "); // Diagonal up-left
}
}
}
}


ComplexityBest CaseAverage CaseWorst CaseExplanation
TCO(m × n)O(m × n)O(m × n)Each element is printed exactly once diagonally
SCO(m × n)O(m × n)O(m × n)For storing input array; no extra space used

No comments:

Post a Comment

Diagonal Traversal

 eg.  1       2       3       4 5      6       7       8 9    10    11     12 13  14   15    16 Output: 1 6 11 16 2 7 12 3 8 4  Approach:...