Broad Network


9.9 Print matrix in zig-zag fashion, in Ruby.

9. Basic Matrix Algorithm Problems in Ruby

Full Course on Data Structures and Algorithms in Ruby

By: Chrysanthus Date Published: 16 May 2026

The reader is advised to read all the lessons (tutorials) in this full course, in the order presented.

Problem

Given a matrix of 2D array of n rows and m columns, print this matrix in ZIG-ZAG fashion as shown in the following figure:

Example 1: 
Input: mat[][] = {{1, 2, 3}
                  {4, 5, 6}
                  {7, 8, 9}}

Output : 1, 2, 4, 7, 5, 3, 6, 8, 9

Example 2: 
Input: mat[][] = {{1,  2,  3,  4,  5}, 
                  {6,  7,  8,  9,  10},
                  {11, 12, 13, 14, 15},
                  {16, 17, 18, 19, 20}};

Output : 1, 2, 6, 11, 7, 3, 4, 8, 12, 16, 17, 13, 9, 5, 10, 14, 18, 19, 15, 20

Solution in O(n x m) Time

The algorithm is as follows:

- Visit the top-left element first. Visit the next element on the right.
- Continue visiting the current minor diagonal elements in the left-downwards direction until meeting the left edge or bottom edge of the matrix.
- If the left edge of the matrix is met and not the bottom edge, visit the next element below.
- Continue visiting the current minor diagonal elements in the right-upwards direction until meeting the top edge or right edge of the matrix.
- If the bottom edge of the matrix was met, and not the left edge, then visit the next element on the right at the bottom edge.
- Continue visiting the current minor diagonal elements in the right-upwards direction until meeting the top edge or right edge of the matrix.
- If the top edge of the matrix is met and not the right edge, visit the next element on the right.
- Continue visiting the current minor diagonal elements in the left-downwards direction until meeting the left edge or bottom edge of the matrix.
- If the right edge of the matrix was met, and not the top edge, then visit the next element below.
- Continue visiting the current minor diagonal elements in the left-downwards direction until meeting the left edge or bottom edge of the matrix.
- Continue repeating the above steps accordingly, until the element at the bottom-right corner of the matrix is met, which will always be met, either from the left or from above.
- Do not forget to consider the cases, where the visit is at the four corners.

There are eight cases to consider: when the visit is at the four corners and when the visit is at the four edges. The case of what happens after the visit of the bottom-right element, does not have to be addressed. This gives rise to seven code segments in a major while-loop.

Indexes

The top most row of the matrix is identified by i=0.
The leftmost column of the matrix is identified by j=0.
The bottommost row of the matrix is identified by i=n-1.
The rightmost column of the matrix is identified by j=m-1.

The program

The program is (read through the code and comments):

def zig_zag_matrix(mat)
  # Determine dimensions automatically
  n = mat.length
  m = mat[0].length
  
  i = 0; j = 0

  while i < n && j < m
    if i == 0 && j == 0    #top-left corner
      print mat[i][j].to_s + ", "
      j += 1    #go right once
      print mat[i][j].to_s + ", "
      while j > 0 && i < n - 1    #end at left or bottom edge
        i += 1
        j -= 1 #go down and left
        print mat[i][j].to_s + ", "
      end
    end

    if j == 0 && i > 0 && i < n - 1    #left edge and not top or bottom ends
      i += 1    #go down once
      print mat[i][j].to_s + ", "
      while i > 0 && j < m - 1    #end at top or right edge
        i -= 1
        j += 1 #go right and up
        print mat[i][j].to_s + ", "
      end
    end

    if i == 0 && j > 0 && j < m - 1    #top edge and not left or right ends
      j += 1 #go right once
      print mat[i][j].to_s + ", "
      while j > 0 && i < n - 1    #end at left or bottom edge
        i += 1
        j -= 1    #go down and left
        print mat[i][j].to_s + ", "
      end
    end

    if i == n - 1 && j == 0 #left-bottom corner
      j += 1 #go right once
      print mat[i][j].to_s + ", "
      while i > 0 && j < m - 1 #end at top or right edge
        i -= 1
        j += 1 #go right and up
        print mat[i][j].to_s + ", "
      end
    end

    if i == 0 && j == m - 1    #top-right corner
      i += 1    #go down once
      print mat[i][j].to_s + ", "
      while j > 0 && i < n - 1    #end at left or bottom edge
        i += 1
        j -= 1 #go down and left
        print mat[i][j].to_s + ", "
      end
    end

    if i > 0 && i < n - 1 && j == m - 1    #right edge and not top or bottom ends
      i += 1    #go down once
      print mat[i][j].to_s + ", "
      while j > 0 && i < n - 1    #end at left or bottom edge
        i += 1
        j -= 1    #go down and left
        print mat[i][j].to_s + ", "
      end
      #bottom-right end of matrix
      if i == n - 1 && j == m - 1
        i += 1
        j += 1    #increase i and j to stop the big while-loop
      end
    end

    if j > 0 && j < m - 1 && i == n - 1    #bottom edge and not left or right ends
      j += 1    #go right once
      print mat[i][j].to_s + ", "
      while i > 0 && j < m - 1    #end at top or right edge
        i -= 1
        j += 1    #go right and up
        print mat[i][j].to_s + ", "
      end
      #bottom-right end of matrix
      if i == n - 1 && j == m - 1
        i += 1
        j += 1    #increase i and j to stop the big while-loop
      end
    end
  end
  puts ""
end

# Main area
=begin
mat = [[1, 2, 3], 
       [4, 5, 6], 
       [7, 8, 9]]
zig_zag_matrix(mat)
=end
=begin
mat2 = [[1,  2,  3,  4,  5], 
        [6,  7,  8,  9,  10], 
        [11, 12, 13, 14, 15], 
        [16, 17, 18, 19, 20]]
zig_zag_matrix(mat2)
=end

Remove the first pair of the block comment markers (/* */). Make the first argument of the called function, "int mat[][3]". Run the program and the output should be:

    1, 2, 4, 7, 5, 3, 6, 8, 9, 

Put back the first pair of the block comment markers (/* */). Remove the second pair of the block comment markers (/* */). Make the first argument of the called function, "int mat[][5]". Run the program and the output should be:

1, 2, 6, 11, 7, 3, 4, 8, 12, 16, 17, 13, 9, 5, 10, 14, 18, 19, 15, 20,

The time complexity is actually O(2 n x m), with the first O(n x m) for populating the input matrix with all the elements, and the second O(n x m) for iterating over all the elements in the matrix in the called function. Since the coefficient (multiplicand of 2) is usually omitted, the time complexity is quoted as O(n x m).

The space complexity is O(n x m), for the input matrix, which is the same as the matrix in the called function (same reference).

Thanks for reading.





Related Links

More Related Links

Cousins

BACK NEXT

Comments


Note: You can use the Search Box above to find articles and discussions of interest.