Open In App

Sort a 2D vector diagonally using Map Data Structure

Last Updated : 31 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a 2D vector mat[][] of integers. The task is to sort the elements of the vectors diagonally from top-left to bottom-right in increasing order.
Examples:
 

Input: mat[][] = 
{{9, 4, 2}, 
 {7, 4, 6},
 {2, 3, 3}}     
Output: 
3 4 2
3 4 6
2 7 9
Explanation:
There are 5 diagonals in this matrix:
1. {2} - No need to sort
2. {7, 3} - Sort - {3, 7}
3. {9, 4, 3} - Sort - {3, 4, 9}
4. {4, 6} - Already sorted
5. {2} - No need to sort



Input: mat[][] =  
{{ 4, 3, 2, 1 }, 
 { 3, 2, 1, 0 }, 
 { 2, 1, 1, 0 }, 
 { 0, 1, 2, 3 }}
Output: 
1 0 0 1 
1 2 1 2 
1 2 3 3 
0 2 3 4 

 

Approach: 
 

  1. All elements in the same diagonal have the same index difference i – j where i is the row number and j is the column number. So we can use a map to store every diagonal at index i – j. 
     
  2. Now we can sort every index of the map using the inbuilt function. 
     
  3. Now in the original matrix, we can insert every diagonal of a matrix stored in map. 
     
  4. Finally, we can print the Matrix. 
     

Below is the implementation of the above approach:
 

CPP




// C++ implementation to sort the
// diagonals of the matrix
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to sort the
// diagonal of the matrix
void SortDiagonal(int mat[4][4],
                  int m, int n)
{
    // Map to store every diagonal
    // in different indices here
    // elements of same diagonal
    // will be stored in same index
    unordered_map<int, vector<int> > mp;
 
    for (int i = 0; i < m; i++)
    {
        for (int j = 0; j < n; j++)
        {
            // Storing diagonal elements
            // in map
            mp[i - j].push_back(mat[i][j]);
        }
    }
 
    // To sort each diagonal in
    // ascending order
    for (int k = -(n - 1); k < m; k++)
    {
        sort(mp[k].begin(),
             mp[k].end());
    }
 
    // Loop to store every diagonal
    // in ascending order
    for (int i = m - 1; i >= 0; i--)
    {
        for (int j = n - 1; j >= 0; j--)
        {
            mat[i][j] = mp[i - j].back();
            mp[i - j].pop_back();
        }
    }
 
    // Loop to print the matrix
    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++)
            cout << mat[i][j] << " ";
        cout << endl;
    }
}
 
// Driven Code
int main()
{
    int arr[4][4] = { { 4, 3, 2, 1 },
                    { 3, 2, 1, 0 },
                    { 2, 1, 1, 0 },
                    { 0, 1, 2, 3 } };
 
    // Sort the Diagonals
    SortDiagonal(arr, 4, 4);
 
    return 0;
}


Java




/*package whatever //do not write package name here */
import java.util.*;
 
class GFG {
 
  // Function to sort the
  // diagonal of the matrix
  static void SortDiagonal(int mat[][], int m, int n)
  {
    // Map to store every diagonal
    // in different indices here
    // elements of same diagonal
    // will be stored in same index
    HashMap<Integer, List<Integer>> mp = new HashMap<>();
 
    for (int i = 0; i < m; i++)
    {
      for (int j = 0; j < n; j++)
      {
        // Storing diagonal elements
        // in map
 
        if(mp.containsKey(i-j)){
          mp.get(i-j).add(mat[i][j]);
        }else{
 
          List<Integer> ll = new ArrayList<>();
          ll.add(mat[i][j]);
          mp.put(i-j,ll);
        }
 
      }
    }
 
    // To sort each diagonal in
    // ascending order
    for(int k = -(n - 1); k < m; k++)
    {
      Collections.sort(mp.get(k));
    }
 
    // Loop to store every diagonal
    // in ascending order
    for(int i = m - 1; i >= 0; i--)
    {
      for(int j = n - 1; j >= 0; j--)
      {
        mat[i][j] = mp.get(i-j).get(mp.get(i-j).size()-1);
        mp.get(i-j).remove(mp.get(i-j).size()-1);
      }
    }
 
    // Loop to print the matrix
    for(int i = 0; i < m; i++) {
      for(int j = 0; j < n; j++)
        System.out.print(mat[i][j]+" ");
      System.out.println();
    }
  }
 
  public static void main (String[] args) {
    int arr[][] = { { 4, 3, 2, 1 },
                   { 3, 2, 1, 0 },
                   { 2, 1, 1, 0 },
                   { 0, 1, 2, 3 } };
 
    // Sort the Diagonals
    SortDiagonal(arr, 4, 4);
 
  }
}
 
// This code is contributed by aadityaburujwale.


Python3




# Python3 implementation to sort the
# diagonals of the matrix
 
# Function to sort the
# diagonal of the matrix
def SortDiagonal(mat, m, n):
   
    # Map to store every diagonal
    # in different indices here
    # elements of same diagonal
    # will be stored in same index
    mp = {}
    for z in range(-5,5):
        mp[z] = []
 
    for i in range(0,m):
        for j in range(0,n):
           
            # Storing diagonal elements
            # in map
            mp[i - j].append(mat[i][j])
 
    # To sort each diagonal in
    # ascending order
    for k in range(-1*(n-1),m):
        mp[k].sort()
 
    # Loop to store every diagonal
    # in ascending order
    for i in range(m-1,-1,-1):
        for j in range(n-1,-1,-1):
            mat[i][j] = mp[i - j][len(mp[i-j])-1]
            mp[i - j].pop(len(mp[i-j])-1)
             
    # Loop to print the matrix
    for i in range(0,m):
        for j in range(0,n):
            print(mat[i][j],end=" ")
        print("")
 
# Driven Code
arr= [ [ 4, 3, 2, 1 ],
        [ 3, 2, 1, 0 ],
        [ 2, 1, 1, 0 ],
        [ 0, 1, 2, 3 ] ]
 
# Sort the Diagonals
SortDiagonal(arr, 4, 4)
 
# This code is contributed by akashish__


C#




using System;
using System.Collections.Generic;
 
public class GFG {
 
  // Function to sort the
  // diagonal of the matrix
  public static void SortDiagonal(int[, ] mat, int m,
                                  int n)
  {
    // Map to store every diagonal
    // in different indices here
    // elements of same diagonal
    // will be stored in same index
    Dictionary<int, List<int> > mp
      = new Dictionary<int, List<int> >();
    for (int i = -100; i < 100; i++) {
      mp.Add(i, new List<int>());
    }
 
    for (int i = 0; i < m; i++) {
      for (int j = 0; j < n; j++) {
        // Storing diagonal elements
        // in map
        mp[i - j].Add(mat[i, j]);
      }
    }
 
    // To sort each diagonal in
    // ascending order
    for (int k = -1 * (n - 1); k < m; k++) {
      mp[k].Sort();
    }
 
    // Loop to store every diagonal
    // in ascending order
    for (int i = m - 1; i >= 0; i--) {
      for (int j = n - 1; j >= 0; j--) {
        mat[i, j] = mp[i - j][mp[i - j].Count - 1];
        mp[i - j].RemoveAt(mp[i - j].Count - 1);
      }
    }
 
    // Loop to print the matrix
    for (int i = 0; i < m; i++) {
      for (int j = 0; j < n; j++)
        Console.Write(mat[i, j] + " ");
      Console.WriteLine("");
    }
  }
 
  static public void Main()
  {
    int[, ] arr = { { 4, 3, 2, 1 },
                   { 3, 2, 1, 0 },
                   { 2, 1, 1, 0 },
                   { 0, 1, 2, 3 } };
 
    // Sort the Diagonals
    SortDiagonal(arr, 4, 4);
  }
}
 
// This code is contributed by akashish__


Javascript




<script>
// Javascript implementation of the above approach
 
// Function to sort the
// diagonal of the matrix
function SortDiagonal(mat, m, n)
{
    // Map to store every diagonal
    // in different indices here
    // elements of same diagonal
    // will be stored in same index
    var mp = {};
    for (var i = 0; i < m; i++)
    {
        for (var j = 0; j < n; j++)
        {
            mp[i - j] = [];
        }
     }
 
    for (var i = 0; i < m; i++)
    {
        for (var j = 0; j < n; j++)
        {
            // Storing diagonal elements
            // in map
            mp[i - j].push(mat[i][j]);
        }
    }
 
    // To sort each diagonal in
    // ascending order
    for (var k = -(n - 1); k < m; k++)
    {
        mp[k].sort();
    }
 
    // Loop to store every diagonal
    // in ascending order
    for (var i = m - 1; i >= 0; i--)
    {
        for (var j = n - 1; j >= 0; j--)
        {
            mat[i][j] = mp[i - j].pop();
        }
    }
 
    // Loop to print the matrix
    for (var i = 0; i < m; i++) {
        for (var j = 0; j < n; j++)
            document.write(mat[i][j] + " " );
        document.write("<br>");
    }
}
 
 
// Driver Code
var arr = [[ 4, 3, 2, 1 ],
    [ 3, 2, 1, 0 ],
    [ 2, 1, 1, 0 ],
    [ 0, 1, 2, 3 ]];
 
// Sort the Diagonals
SortDiagonal(arr, 4, 4);
</script>


Output: 

1 0 0 1 
1 2 1 2 
1 2 3 3 
0 2 3 4 

 

Time complexity : O(mnlog(mn)), where m is the number of rows and n is the number of columns of the matrix

Space complexity : O(m*n) as it uses an unordered_map container to store each diagonal of the matrix.



Similar Reads

Sort a 2D vector diagonally
Given a 2D vector of NxM integers. The task is to sort the elements of the vectors diagonally from top-left to bottom-right in decreasing order.Examples: Input: arr[][] = { { 10, 2, 3 }, { 4, 5, 6 }, {7, 8, 9 } } Output: 10 6 3 8 9 2 7 4 5Input: arr[][] = { { 10, 2, 43 }, { 40, 5, 16 }, { 71, 8, 29 }, {1, 100, 5} } Output: 29 16 43 40 10 2 100 8 5
15+ min read
Check if it is possible to reach vector B by rotating vector A and adding vector C to it
Given three 2-Dimensional vector co-ordinates A, B and C. The task is to perform below operations any number of times on vector A to get vector B : Rotate the vector 90 degrees clockwise.Add vector C to it. Print "YES" B is obtained using the above operations, else Print "NO".Examples: Input: Vector A: 2 3, Vector B: 2 3, Vector C: 0 0 Output: YES
9 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
Remove duplicates from unsorted array using Map data structure
Given an unsorted array of integers, print the array after removing the duplicate elements from it. We need to print distinct array elements according to their first occurrence. Examples: Input : arr[] = { 1, 2, 5, 1, 7, 2, 4, 2} Output : 1 2 5 7 4 Explanation : {1, 2} appear more than one time. Approach : Take a hash map, which will store all the
4 min read
Static Data Structure vs Dynamic Data Structure
Data structure is a way of storing and organizing data efficiently such that the required operations on them can be performed be efficient with respect to time as well as memory. Simply, Data Structure are used to reduce complexity (mostly the time complexity) of the code. Data structures can be two types : 1. Static Data Structure 2. Dynamic Data
4 min read
Diagonally Dominant Matrix
In mathematics, a square matrix is said to be diagonally dominant if for every row of the matrix, the magnitude of the diagonal entry in a row is larger than or equal to the sum of the magnitudes of all the other (non-diagonal) entries in that row. More precisely, the matrix A is diagonally dominant if For example, The matrix is diagonally dominant
6 min read
Minimize moves to reach a target point from origin by moving horizontally or diagonally in right direction
Given source (X1, Y1) as (0, 0) and a target (X2, Y2) on a 2-D plane. In one step, either of (X1+1, Y1+1) or (X1+1, Y1) can be visited from (X1, Y1). The task is to calculate the minimum moves required to reach the target using given moves. If the target can't be reached, print "-1". Examples: Input: X2 = 1, Y2 = 0Output: 1Explanation: Take 1 step
4 min read
Print the matrix diagonally downwards
Given a matrix of size n*n, print the matrix in the following pattern. Output: 1 2 5 3 6 9 4 7 10 13 8 11 14 12 15 16 Examples: Input :matrix[2][2]= { {1, 2}, {3, 4} } Output : 1 2 3 4 Input :matrix[3][3]= { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} } Output : 1 2 4 3 5 7 6 8 9 Implementation: Following is the C++ implementation for the above pattern. C/C++
5 min read
Find the side of the squares which are inclined diagonally and lined in a row
Given here are n squares which are inclined and touch each other externally at vertices, and are lined up in a row.The distance between the centers of the first and last square is given.The squares have equal side length.The task is to find the side of each square.Examples: Input :d = 42, n = 4 Output :The side of each square is 9.899Input :d = 54,
4 min read
Minimum number of steps to convert a given matrix into Diagonally Dominant Matrix
Given a matrix of order NxN, the task is to find the minimum number of steps to convert given matrix into Diagonally Dominant Matrix. In each step, the only operation allowed is to decrease or increase any element by 1.Examples: Input: mat[][] = {{3, 2, 4}, {1, 4, 4}, {2, 3, 4}} Output: 5 Sum of the absolute values of elements of row 1 except the d
6 min read
Article Tags :
Practice Tags :