Spiral Traversal on a Matrix
Understanding the Problem
The goal is to traverse a matrix in a spiral order.
Method 1: Using Iterative Approach
This method uses an iterative approach to traverse the matrix in spiral order.
public class SpiralTraversal {
public static void spiralTraversal(int[][] matrix) {
int top = 0, bottom = matrix.length - 1;
int left = 0, right = matrix[0].length - 1;
while (top <= bottom && left <= right) {
for (int i = left; i <= right; i++) {
System.out.print(matrix[top][i] + " ");
}
top++;
for (int i = top; i <= bottom; i++) {
System.out.print(matrix[i][right] + " ");
}
right--;
if (top <= bottom) {
for (int i = right; i >= left; i--) {
System.out.print(matrix[bottom][i] + " ");
}
bottom--;
}
if (left <= right) {
for (int i = bottom; i >= top; i--) {
System.out.print(matrix[i][left] + " ");
}
left++;
}
}
}
public static void main(String[] args) {
int[][] matrix = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12},
{13, 14, 15, 16}
};
System.out.print("Spiral Traversal: ");
spiralTraversal(matrix);
System.out.println();
}
}
Output:
Spiral Traversal: 1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10
Method 2: Using Recursion
This method uses recursion to achieve spiral traversal.
public class SpiralTraversal {
public static void spiralUtil(int[][] matrix, int top, int bottom, int left, int right) {
if (top > bottom || left > right) return;
for (int i = left; i <= right; i++) {
System.out.print(matrix[top][i] + " ");
}
top++;
for (int i = top; i <= bottom; i++) {
System.out.print(matrix[i][right] + " ");
}
right--;
if (top <= bottom) {
for (int i = right; i >= left; i--) {
System.out.print(matrix[bottom][i] + " ");
}
bottom--;
}
if (left <= right) {
for (int i = bottom; i >= top; i--) {
System.out.print(matrix[i][left] + " ");
}
left++;
}
spiralUtil(matrix, top, bottom, left, right);
}
public static void spiralTraversal(int[][] matrix) {
spiralUtil(matrix, 0, matrix.length - 1, 0, matrix[0].length - 1);
}
public static void main(String[] args) {
int[][] matrix = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12},
{13, 14, 15, 16}
};
System.out.print("Spiral Traversal: ");
spiralTraversal(matrix);
System.out.println();
}
}
Output:
Spiral Traversal: 1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10