880222. Print matrix in zig-zag fashion
Easy
Print matrix in zig-zag fashion
Slug: print-matrix-in-zig-zag-fashion--122748
Difficulty: Easy
Id: 880222
Topic Tags: None
Company Tags: None
Summary
Given a square matrix, print it in a zig-zag fashion. The input matrix is represented as a 2D array where each row is a line and each element in the array represents a node in the matrix. This problem involves printing the elements of the matrix in an alternating diagonal pattern.
Detailed Explanation
The algorithm for solving this problem can be broken down into two main steps:
- Determine whether we are currently moving up (i.e., from left to right) or down (i.e., from right to left).
- Print the current element and then update our direction based on the row number.
Here's a step-by-step breakdown of the solution:
1. Initialize an index `i` to 0.
2. Start with the first element in the matrix, which is at position (0, 0).
3. While printing elements, keep track of whether we are moving up or down.
- If we are moving up and have reached the last row, switch direction to down.
- If we are moving down and have reached the last column, switch direction to up.
4. When switching direction, update `i` accordingly:
- If moving up, increment `i`.
- If moving down, decrement `i`.
5. Continue this process until all elements in the matrix have been printed.
Time Complexity: O(m*n) where m and n are the dimensions of the matrix.
Space Complexity: O(1), as we only use a constant amount of space to store our variables.
Optimized Solutions
#### Java
public class Main {
public static void printZigZag(int[][] matrix) {
int rows = matrix.length;
int cols = matrix[0].length;
boolean up = true;
for (int i = 0; i < rows * 2 - 1; i++) {
for (int j = (i % 2 == 0 ? 0 : cols - 1); j <= ((i + 1) % 2 ? 0 : cols - 1); j += (i % 2 == 0 ? 1 : -1)) {
System.out.print(matrix[i / 2][j] + " ");
}
System.out.println();
}
}
public static void main(String[] args) {
int[][] matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
printZigZag(matrix);
}
}