Print a matrix in alternate manner (left to right then right to left) in C++

C++Server Side ProgrammingProgramming

In this problem, we are given a 2D array. Our task is to print all the elements of the array starting from the first row, from left to right, then right to left in the next row and again from left to right and so on.

Let’s take an example to understand the problem.

Input: array = {
   {2, 5}
   {4, 9}
}
Output: 2 5 9 4

To solve this problem, we will print elements in the given direction (LtoR and RtoL) of a row. And a flag element to show the direction of printing will switch after every iteration.

This is an easy and efficient solution with time complexity = O(R*C)

Example

Program to show the implementation of our solution

 Live Demo

#include<iostream>
using namespace std;
#define R 3
#define C 3
void printAlternateMatrix(int arr[R][C]) {
   bool direction = true;
   for (int i=0; i<R; i++){
      if (direction){
         for (int j=0; j<C; j++)
            printf("%d ", arr[i][j]);
      } else{
         for (int j=C-1; j>=0; j--)
            printf("%d ",arr[i][j]);
      }
      direction = !direction;
   }
}
int main() {
   int arr[][C] = {
      { 23 , 50 , 4 },
      { 89 , 9 , 34 },
      { 75 , 1 , 61 },
   };
   cout<<"Matrix in alternate order is :\n";
   printAlternateMatrix(arr);
   return 0;
}

Output

The matrix in alternate order is −

23 50 4 34 9 89 75 1 61
raja
Published on 27-Jan-2020 11:00:20
Advertisements