The Wayback Machine - https://web.archive.org/web/20240909154700/https://www.geeksforgeeks.org/print-matrix-in-zig-zag-fashion/
Open In App

Print matrix in zig-zag fashion

Last Updated : 18 Apr, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
Show Topics
Solve Problem
Easy
68.08%
71.1K

Given a matrix of 2D array of n rows and m columns. Print this matrix in ZIG-ZAG fashion as shown in figure. 

matrix_zag-zag

Example: 

Input:
{{1, 2, 3}
{4, 5, 6}
{7, 8, 9}}

Output: 1 2 4 7 5 3 6 8 9

Approach:

This approach uses a diagonal traversal technique to print the matrix in a zig-zag pattern. It iterates through the matrix diagonally, switching between incrementing the row and column indices based on the current position. This creates a zig-zag path that covers all elements of the matrix.

Below is the implementation of the above approach:

C++
/* C++ Program to print matrix in Zig-zag pattern*/
#include <iostream>
using namespace std;
#define C 3

// Utility function to print matrix
// in zig-zag form
void zigZagMatrix(int arr[][C], int n, int m)
{
    int row = 0, col = 0;

    // Boolean variable that will true if we
    // need to increment 'row' value otherwise
    // false- if increment 'col' value
    bool row_inc = 0;

    // Print matrix of lower half zig-zag pattern
    int mn = min(m, n);
    for (int len = 1; len <= mn; ++len) {
        for (int i = 0; i < len; ++i) {
            cout << arr[row][col] << " ";

            if (i + 1 == len)
                break;
            // If row_increment value is true
            // increment row and decrement col
            // else decrement row and increment
            // col
            if (row_inc)
                ++row, --col;
            else
                --row, ++col;
        }

        if (len == mn)
            break;

        // Update row or col value according
        // to the last increment
        if (row_inc)
            ++row, row_inc = false;
        else
            ++col, row_inc = true;
    }

    // Update the indexes of row and col variable
    if (row == 0) {
        if (col == m - 1)
            ++row;
        else
            ++col;
        row_inc = 1;
    }
    else {
        if (row == n - 1)
            ++col;
        else
            ++row;
        row_inc = 0;
    }

    // Print the next half zig-zag pattern
    int MAX = max(m, n) - 1;
    for (int len, diag = MAX; diag > 0; --diag) {

        if (diag > mn)
            len = mn;
        else
            len = diag;

        for (int i = 0; i < len; ++i) {
            cout << arr[row][col] << " ";

            if (i + 1 == len)
                break;

            // Update row or col value according
            // to the last increment
            if (row_inc)
                ++row, --col;
            else
                ++col, --row;
        }

        // Update the indexes of row and col variable
        if (row == 0 || col == m - 1) {
            if (col == m - 1)
                ++row;
            else
                ++col;

            row_inc = true;
        }

        else if (col == 0 || row == n - 1) {
            if (row == n - 1)
                ++col;
            else
                ++row;

            row_inc = false;
        }
    }
}

// Driver code
int main()
{
    int matrix[][3] = { { 1, 2, 3 },
                        { 4, 5, 6 },
                        { 7, 8, 9 } };
    zigZagMatrix(matrix, 3, 3);

    return 0;
}
Java
/* Java Program to print matrix in Zig-zag pattern*/
class GFG {
  static final int C = 3;

  // Utility function to print matrix
  // in zig-zag form
  static void zigZagMatrix(int arr[][], int n, int m) {
    int row = 0, col = 0;

    // Boolean variable that will true if we
    // need to increment 'row' value otherwise
    // false- if increment 'col' value
    boolean row_inc = false;

    // Print matrix of lower half zig-zag pattern
    int mn = Math.min(m, n);
    for (int len = 1; len <= mn; ++len) {
      for (int i = 0; i < len; ++i) {
        System.out.print(arr[row][col] + " ");

        if (i + 1 == len)
          break;
        // If row_increment value is true
        // increment row and decrement col
        // else decrement row and increment
        // col
        if (row_inc) {
          ++row;
          --col;
        } else {
          --row;
          ++col;
        }
      }

      if (len == mn)
        break;

      // Update row or col value according
      // to the last increment
      if (row_inc) {
        ++row;
        row_inc = false;
      } else {
        ++col;
        row_inc = true;
      }
    }

    // Update the indexes of row and col variable
    if (row == 0) {
      if (col == m - 1)
        ++row;
      else
        ++col;
      row_inc = true;
    } else {
      if (row == n - 1)
        ++col;
      else
        ++row;
      row_inc = false;
    }

    // Print the next half zig-zag pattern
    int MAX = Math.max(m, n) - 1;
    for (int len, diag = MAX; diag > 0; --diag) {

      if (diag > mn)
        len = mn;
      else
        len = diag;

      for (int i = 0; i < len; ++i) {
        System.out.print(arr[row][col] + " ");

        if (i + 1 == len)
          break;

        // Update row or col value according
        // to the last increment
        if (row_inc) {
          ++row;
          --col;
        } else {
          ++col;
          --row;
        }
      }

      // Update the indexes of row and col variable
      if (row == 0 || col == m - 1) {
        if (col == m - 1)
          ++row;
        else
          ++col;

        row_inc = true;
      }

      else if (col == 0 || row == n - 1) {
        if (row == n - 1)
          ++col;
        else
          ++row;

        row_inc = false;
      }
    }
  }
  // Driver code
  public static void main(String[] args) {
    int matrix[][] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
    zigZagMatrix(matrix, 3, 3);
  }
}
// This code is contributed by Anant Agarwal.
Python3
# Program to print matrix in Zig-zag pattern

matrix =[
            [ 1, 2, 3,],
            [ 4, 5, 6 ],
            [ 7, 8, 9 ],
        ]
rows=3
columns=3
  
solution=[[] for i in range(rows+columns-1)]

for i in range(rows):
    for j in range(columns):
        sum=i+j
        if(sum%2 ==0):

            #add at beginning
            solution[sum].insert(0,matrix[i][j])
        else:

            #add at end of the list
            solution[sum].append(matrix[i][j])
        
            
# print the solution as it as
for i in solution:
    for j in i:
        print(j,end=" ")
        

      
C#
// C# Program to print matrix
// in Zig-zag pattern
using System;

class GFG {
    static int C = 3;

    // Utility function to print
    // matrix in zig-zag form
    static void zigZagMatrix(int[, ] arr, int n, int m)
    {
        int row = 0, col = 0;

        // Boolean variable that will
        // true if we need to increment
        // 'row' valueotherwise false-
        // if increment 'col' value
        bool row_inc = false;

        // Print matrix of lower half
        // zig-zag pattern
        int mn = Math.Min(m, n);
        for (int len = 1; len <= mn; ++len) {
                for (int i = 0; i < len; ++i) {

                Console.Write(arr[row, col] + " ");

                if (i + 1 == len)
                    break;

                // If row_increment value is true
                // increment row and decrement col
                // else decrement row and increment
                // col
                if (row_inc) {
                    ++row;
                    --col;
                }
                else {
                    --row;
                    ++col;
                }
            }

            if (len == mn)
                break;

            // Update row or col value
            // according to the last
            // increment
            if (row_inc) {
                    ++row;
                    row_inc = false;
            }
            else {
                ++col;
                row_inc = true;
            }
        }

        // Update the indexes of row
        // and col variable
        if (row == 0) {
            if (col == m - 1)
                ++row;
            else
                ++col;
            row_inc = true;
        }
        else {
            if (row == n - 1)
                ++col;
            else
                ++row;
            row_inc = false;
        }

        // Print the next half
        // zig-zag pattern
        int MAX = Math.Max(m, n) - 1;
        for (int len, diag = MAX; diag > 0; --diag) {

            if (diag > mn)
                    len = mn;
            else
                len = diag;

            for (int i = 0; i < len; ++i) {
                    Console.Write(arr[row, col] + " ");

                if (i + 1 == len)
                    break;

                // Update row or col value
                // according to the last
                // increment
                if (row_inc) {
                        ++row;
                        --col;
                }
                else {
                    ++col;
                    --row;
                }
            }

            // Update the indexes of
            // row and col variable
            if (row == 0 || col == m - 1) {
                if (col == m - 1)
                    ++row;
                else
                    ++col;

                row_inc = true;
            }

            else if (col == 0 || row == n - 1) {
                if (row == n - 1)
                    ++col;
                else
                    ++row;

                row_inc = false;
            }
        }
    }

    // Driver code
    public static void Main()
    {
        int[, ] matrix = { { 1, 2, 3 },
                        { 4, 5, 6 },
                        { 7, 8, 9 } };
        zigZagMatrix(matrix, 3, 3);
    }
}

// This code is contributed by vt_m.
JavaScript
// Javascript Program to print matrix in Zig-zag pattern
var n = 3, m = 3;
var a = [[ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ]];
var zigZagMatrix=function(arr, n, m)
{
    var row = 0;
    var col = 0;
 
    // Variable that will be 1 if we
    // need to increment 'row' value and 0 otherwise
    // if we need to increment 'col' value
    var row_inc = 0;
 
    // print matrix of lower half zig-zag pattern
    var mn = Math.min(m, n);
    for (var len = 1; len <= mn; ++len) {
        for (var i = 0; i < len; ++i) {
            console.log(arr[row][col]);
            console.log(" ");
 
            if (i + 1 == len)
                break;
            // If row_increment value is true
            // increment row and decrement col
            // else decrement row and increment col
            if (row_inc)
                ++row, --col;
            else
                --row, ++col;
        }
 
        if (len == mn)
            break;
 
        // Update row or col value according
        // to the last increment
        if (row_inc)
            ++row, row_inc = false;
        else
            ++col, row_inc = true;
    }
 
    // Update the indexes of row and col variable
    if (row == 0) {
        if (col == m - 1)
            ++row;
        else
            ++col;
        row_inc = 1;
    }
    else {
        if (row == n - 1)
            ++col;
        else
            ++row;
        row_inc = 0;
    }
 
    // Print the next half zig-zag pattern
    var MAX = Math.max(m, n) - 1;
    for (var len, diag = MAX; diag > 0; --diag) {
 
        if (diag > mn)
            len = mn;
        else
            len = diag;
 
        for (var i = 0; i < len; ++i) {
            console.log(arr[row][col]);
            console.log(" ");
            if (i + 1 == len)
                break;
 
            // Update row or col value according
            // to the last increment
            if (row_inc)
                ++row, --col;
            else
                ++col, --row;
        }
 
        // Update the indexes of row and col variable
        if (row == 0 || col == m - 1) {
            if (col == m - 1)
                ++row;
            else
                ++col;
 
            row_inc = true;
        }
 
        else if (col == 0 || row == n - 1) {
            if (row == n - 1)
                ++col;
            else
                ++row;
            row_inc = false;
        }
    }
}
zigZagMatrix(a, 3, 3);
 
// This code is contributed by Sajal Aggarwal.
PHP
<?php
// PHP Program to print 
// matrix in Zig-zag pattern
$C = 3;

// Utility function 
// to print matrix
// in zig-zag form
function zigZagMatrix($arr,
                      $n, $m)
{
    $row = 0; $col = 0;

    // Boolean variable that
    // will true if we need 
    // to increment 'row' 
    // value otherwise false-
    // if increment 'col' value
    $row_inc = false;

    // Print matrix of lower
    // half zig-zag pattern
    $mn = min($m, $n);
    for ($len = 1; 
         $len <= $mn; $len++) 
    {
        for ($i = 0; 
             $i < $len; $i++) 
        {
            echo ($arr[$row][$col]." ");

            if ($i + 1 == $len)
                break;
                
            // If row_increment value 
            // is true increment row 
            // and decrement col else 
            // decrement row and 
            // increment col
            if ($row_inc)
            {
                $row++; $col--;
            }
            else
            {
                $row--; $col++;
            }
        }

        if ($len == $mn)
            break;

        // Update row or col
        // value according
        // to the last increment
        if ($row_inc) 
        {
            ++$row; $row_inc = false;
        }
        else 
        {
            ++$col; $row_inc = true;
        }
    }

    // Update the indexes of
    // row and col variable
    if ($row == 0) 
    {
        if ($col == $m - 1)
            ++$row;
        else
            ++$col;
        $row_inc = 1;
    }
    else 
    {
        if ($row == $n - 1)
            ++$col;
        else
            ++$row;
        $row_inc = 0;
    }

    // Print the next half
    // zig-zag pattern
    $MAX = max($m, $n) - 1;
    for ($len, $diag = $MAX;
         $diag > 0; --$diag) 
    {
        if ($diag > $mn)
            $len = $mn;
        else
            $len = $diag;

        for ($i = 0; 
             $i < $len; ++$i)
        {
            echo($arr[$row][$col] . " ");

            if ($i + 1 == $len)
                break;

            // Update row or col 
            // value according to
            // the last increment
            if ($row_inc)
            {
                ++$row; --$col;
            }
            else
            {
                ++$col; --$row;
            }
        }

        // Update the indexes of
        // row and col variable
        if ($row == 0 || 
            $col == $m - 1) 
        {
            if ($col == $m - 1)
                ++$row;
            else
                ++$col;

            $row_inc = true;
        }

        else if ($col == 0 || 
                 $row == $n - 1) 
        {
            if ($row == $n - 1)
                ++$col;
            else
                ++$row;

            $row_inc = false;
        }
    }
}

// Driver code
$matrix = array(array(1, 2, 3),
                array(4, 5, 6),
                array(7, 8, 9));
                
zigZagMatrix($matrix, 3, 3);

// This code is contributed by 
// Manish Shaw(manishshaw1)
?>

Output
1 2 4 7 5 3 6 8 9 

Time complexity: O(n*m)
Auxiliary space: O(1), since no extra space has been taken.



Previous Article
Next Article

Similar Reads

Print matrix in zig-zag fashion from the last column
Given a matrix of 2-Dimensional array of n rows and n columns. Print this matrix in ZIG-ZAG fashion starting from column n-1 as shown in the figure below. Examples: Input: mat[][] = 1 2 3 4 5 6 7 8 9 Output: 3 2 6 9 5 1 4 8 7 Input: mat[][] = 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 Output: 4 3 8 12 7 2 1 6 11 16 15 10 5 9 14 13 Algorithm: Start trav
12 min read
Rearrange a Linked List in Zig-Zag fashion | Set-2
Given a linked list, rearrange it such that converted list should be of the form a &lt; b &gt; c &lt; d &gt; e &lt; f .. where a, b, c.. are consecutive data node of linked list. Note that it is not allowed to swap data. Examples: Input: 1-&gt;2-&gt;3-&gt;4 Output: 1-&gt;3-&gt;2-&gt;4 Input: 11-&gt;15-&gt;20-&gt;5-&gt;10 Output: 11-&gt;20-&gt;5-
13 min read
Converting an array of integers into Zig-Zag fashion!
Let us elaborate the problem a little more. Basically, we are given an array of integers and we need to arrange this array in an order such that 1st element is lesser than 2nd element, 2nd element is greater than 3rd element, 3rd element is lesser than 4th element, 4th element is greater than 5th element, so on. In short, the order of elements in t
4 min read
Convert Array into Zig-Zag fashion (arr[i-1] < arr[i] > arr[i+1])
Given an array of distinct elements of size N, the task is to rearrange the elements of the array in a zig-zag fashion, i.e., the elements are arranged as smaller, then larger, then smaller, and so on. There can be more than one arrangement that follows the form: arr[0] &lt; arr[1] &gt; arr[2] &lt; arr[3] &gt; arr[4] &lt; ... Examples: Input: N = 7
12 min read
Rearrange a Linked List in Zig-Zag fashion
Given a linked list, rearrange it such that the converted list should be of the form a &lt; b &gt; c &lt; d &gt; e &lt; f … where a, b, c… are consecutive data nodes of the linked list. Examples: Input: 1-&gt;2-&gt;3-&gt;4 Output: 1-&gt;3-&gt;2-&gt;4 Explanation : 1 and 3 should come first before 2 and 4 in zig-zag fashion, So resultant linked-list
15+ min read
Javascript Program For Converting Array Into Zig-Zag Fashion
Given an array of DISTINCT elements, rearrange the elements of array in zig-zag fashion in O(n) time. The converted array should be in form a &lt; b &gt; c &lt; d &gt; e &lt; f. Example: Input: arr[] = {4, 3, 7, 8, 6, 2, 1} Output: arr[] = {3, 7, 4, 8, 2, 6, 1} Input: arr[] = {1, 4, 3, 2} Output: arr[] = {1, 4, 2, 3} A Simple Solution is to first s
3 min read
Javascript Program For Rearranging A Linked List In Zig-Zag Fashion
Given a linked list, rearrange it such that the converted list should be of the form a &lt; b &gt; c &lt; d &gt; e &lt; f … where a, b, c… are consecutive data nodes of the linked list. Examples: Input: 1-&gt;2-&gt;3-&gt;4 Output: 1-&gt;3-&gt;2-&gt;4 Explanation: 1 and 3 should come first before 2 and 4 in zig-zag fashion, So resultant linked-list
5 min read
Given 1's, 2's, 3's ......k's print them in zig zag way.
Given number of rows and columns. And given number of 1's, 2's, 3's ......k's which needs to be printed. Print them in a zig-zag way. It is guaranteed that n*m = number of 1's + 2's + 3's + ...... + k's Examples: Input : 2 3 2 1 2 1 Output : 1 1 2 4 3 3 Explanation : Here number of rows are 2 and number of columns are 3 and number of 1's are 2 numb
10 min read
Print Concatenation of Zig-Zag String in 'n' Rows
Given a string and number of rows 'n'. Print the string formed by concatenating n rows when input string is written in row-wise Zig-Zag fashion. Examples: Input: str = "ABCDEFGH" n = 2 Output: "ACEGBDFH" Explanation: Let us write input string in Zig-Zag fashion in 2 rows. A C E G B D F H Now concatenate the two rows and ignore spaces in every row.
12 min read
Arrange numbers 1 to N^2 in a Zig-Zag Matrix in ascending order
Given a positive integer N, the task is to print an N × N zig-zag matrix consisting of numbers from 1 to N2, such that the ZigZag traversal of the matrix yields the number in ascending order.Examples: Input: N = 3 Output: 1 2 4 3 5 7 6 8 9 Explanation: Input: N = 4 Output: 1 2 4 7 3 5 8 11 6 9 12 14 10 13 15 16 Approach: The required matrix can be
7 min read
Number of steps required to reach point (x,y) from (0,0) using zig-zag way
Given a coordinate (x, y). The task is to calculate the number of steps required to reach point (x, y) from (0, 0) using zig-zag way and you cannot travel in straight line for more than 1 unit. Also, start moving along Y axis.For example we can reach the Point denoted by red color in the respective ways as shown in the below diagram: Examples: Inpu
4 min read
Vertical Zig-Zag traversal of a Tree
Given a Binary Tree, the task is to print the elements in the Vertical Zig-Zag traversal order. Vertical Zig-Zag traversal of a tree is defined as: Print the elements of the first level in the order from right to left, if there are no elements left then skip to the next level.Print the elements of the last level in the order from left to right, if
15 min read
Zig-Zag level order traversal of Binary Tree after every K levels
Given a binary tree and an integer K, the task is to print the level order traversal in such a way that first K levels are printed from left to right, next K levels are printed from right to left, then next K levels are from left to right and so on. Examples: Input: K = 1 1 / \ 2 3 / \ / 4 9 8Output:1 3 24 9 8Explanation: In the above example, firs
10 min read
Concatenation of Zig-Zag String in N Rows
The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) P A H N A P L S I I G Y I R And then read line by line: PAHNAPLSIIGYIR. Therefore, for given string str and an integer N, the task is to print the string formed by concatenating
6 min read
Longest Zig-Zag Subsequence
The longest Zig-Zag subsequence problem is to find length of the longest subsequence of given sequence such that all elements of this are alternating. If a sequence {x1, x2, .. xn} is alternating sequence then its element satisfy one of the following relation : x1 &lt; x2 &gt; x3 &lt; x4 &gt; x5 &lt; …. xn or x1 &gt; x2 &lt; x3 &gt; x4 &lt; x5 &gt;
15+ min read
Print Binary Search Tree in Min Max Fashion
Given a Binary Search Tree (BST), the task is to print the BST in min-max fashion. What is min-max fashion? A min-max fashion means you have to print the maximum node first then the minimum then the second maximum then the second minimum and so on. Examples: Input: 100 / \ 20 500 / \ 10 30 \ 40 Output: 10 500 20 100 30 40 Input: 40 / \ 20 50 / \ \
10 min read
Traverse the matrix in Diagonally Bottom-Up fashion using Recursion
Given a matrix mat[][] of size N x N, the task is to traverse the matrix Diagonally in Bottom-up fashion using recursion.Diagonally Bottom-up Traversal: Traverse the major-diagonal of the matrix.Traverse the bottom diagonal to the major-diagonal of the matrix.Traverse the up diagonal to the major-diagonal of the matrix.Similarly, Traverse the matri
9 min read
Rearrange Odd and Even values in Alternate Fashion in Ascending Order
Given an array of integers (both odd and even), the task is to arrange them in such a way that odd and even values come in alternate fashion in non-decreasing order(ascending) respectively. If the smallest value is Even then we have to print Even-Odd pattern.If the smallest value is Odd then we have to print Odd-Even pattern. Note: No. of odd eleme
15+ min read
Arrange N elements in circular fashion such that all elements are strictly less than sum of adjacent elements
Given an array of N integers, the task is to arrange them in a circular arrangement in such a way that the element is strictly less than the sum of its adjacent elements. In case such an arrangement is not possible, then print -1. Note that there can be multiple ways of arranging the elements such that the condition is satisfied and the task is to
8 min read
Count non-adjacent subsets from numbers arranged in Circular fashion
Given that N people are sitting in a circular queue numbered from 1 to N, the task is to count the number of ways to select a subset of them such that no two consecutive are sitting together. The answer could be large, so compute the answer modulo 109 + 7. Note that an empty subset is also a valid subset. Examples: Input: N = 2 Output: 3 All possib
5 min read
Minimize operations to convert each node of N-ary Tree from initial[i] to final[i] by flipping current node subtree in alternate fashion
Given an N-ary Tree consisting of N nodes valued from [0, N - 1] and two binary arrays initial[] and final[] of size N such that initial[i] represents the value assigned to the node i, the task is to find the minimum number of operations required to convert each value of nodes initial[i] to final[i] by flipping the value of the node, its grandchild
11 min read
Random number generator in arbitrary probability distribution fashion
Given n numbers, each with some frequency of occurrence. Return a random number with probability proportional to its frequency of occurrence. Example: Let following be the given numbers. arr[] = {10, 30, 20, 40} Let following be the frequencies of given numbers. freq[] = {1, 6, 2, 1} The output should be 10 with probability 1/10 30 with probability
11 min read
Convert a Binary Tree into Doubly Linked List in spiral fashion
Given a Binary Tree, convert it into a Doubly Linked List where the nodes are represented Spirally. The left pointer of the binary tree node should act as a previous node for created DLL and the right pointer should act as the next node. The solution should not allocate extra memory for DLL nodes. It should use binary tree nodes for creating DLL i.
14 min read
Construct a complete binary tree from given array in level order fashion
Given an array of elements, our task is to construct a complete binary tree from this array in a level order fashion. That is, elements from the left in the array will be filled in the tree level-wise starting from level 0.Examples: Input : arr[] = {1, 2, 3, 4, 5, 6}Output : Root of the following tree 1 / \ 2 3 / \ / 4 5 6Input: arr[] = {1, 2, 3, 4
11 min read
Print Matrix after multiplying Matrix elements N times
Given a square matrix mat[][] and an integer N, the task is to print the matrix after multiplying the matrix N times. Examples: Input: mat[][] = {{1, 2, 3}, {3, 4, 5}, {6, 7, 9}}, N = 2Output:25 31 4045 57 7481 103 134 Input: mat[][] = {{1, 2}, {3, 4}}, N = 3Output:37 5481 118 Approach: The idea is to use the Matrix Multiplication identity matrix.
9 min read
Generate matrix from given Sparse Matrix using Linked List and reconstruct the Sparse Matrix
Given a sparse matrix mat[][] of dimensions N*M, the task is to construct and represent the original matrix using a Linked List and reconstruct the givensparse matrix. Examples: Input: mat[][] = {{0, 1, 0, 0, 0}, {0, 1, 0, 0, 0}, {0, 0, 2, 0, 0}, {0, 3, 0, 0, 4}, {0, 0, 5, 0, 0}}Output:Linked list representation: (4, 2, 5) ? (3, 4, 4) ? (3, 1, 3) ?
15+ min read
Generate a Matrix such that given Matrix elements are equal to Bitwise OR of all corresponding row and column elements of generated Matrix
Given a matrix B[][] of dimensions N * M, the task is to generate a matrix A[][] of same dimensions that can be formed such that for any element B[i][j] is equal to Bitwise OR of all elements in the ith row and jth column of A[][]. If no such matrix exists, print "Not Possible". Otherwise, print the matrix A[][]. Examples: Input: B[][] = {{1, 1, 1}
11 min read
Print shortest path to print a string on screen
Given a screen containing alphabets from A-Z, we can go from one character to another characters using a remote. The remote contains left, right, top and bottom keys.Find shortest possible path to type all characters of given string using the remote. Initial position is top left and all characters of input string should be printed in order.Screen:
8 min read
Print matrix after applying increment operations in M ranges
Given a 2-D matrix mat[][] of size N * N, initially all the elements of the matrix are 0. A number of queries(M ranges) need to be performed on the matrix where each query consists of four integers X1, Y1, X2 and Y2, the task is to add 1 to all the cells between mat[X1][Y1] and mat[X2][Y2] (including both) and print the contents of the updated matr
8 min read
Python | Print unique rows in a given boolean matrix using Set with tuples
Given a binary matrix, print all unique rows of the given matrix. Order of row printing doesn't matter. Examples: Input: mat = [[0, 1, 0, 0, 1], [1, 0, 1, 1, 0], [0, 1, 0, 0, 1], [1, 1, 1, 0, 0]] Output: (1, 1, 1, 0, 0) (0, 1, 0, 0, 1) (1, 0, 1, 1, 0) We have existing solution for this problem please refer link. We can solve this problem in python
2 min read
Article Tags :
Practice Tags :