[Expected Approach - 1] Recursive Approach - O(n^2) Time and O(n^2) Space
To recursively construct a linked matrix from a 2D matrix, start at the (0, 0) position of the given matrix and create a node for each matrix element. Each node’s right pointer links to the next element in the same row, while its down pointer connects to the element directly below in the column. If the current position is out of bounds, return NULL to end recursive call. This process continues recursively, creating and linking nodes until the entire matrix is transformed into a linked matrix with appropriate horizontal and vertical connections.
Follow the steps below to solve the problem:
First, create a variable of Node type, which will store the value and the addresses of its right and bottom nodes corresponding to a cell in the matrix.
Recursively do the following steps for any cell in the matrix:
If the cell is out of bounds, return null.
Create a new Node with the value from the matrix for the current cell.
Recursively construct the right node for the next cell in the row.
Recursively construct the down node for the next cell in the column.
Finally return the root Node.
Below is the implementation of the above approach:
C++
// C++ to implement linked matrix // from a 2D matrix recursively #include<bits/stdc++.h>usingnamespacestd;classNode{public:intdata;Node*right,*down;Node(intx){data=x;right=down=nullptr;}};// Function to recursively construct the linked matrix // from a given 2D vectorNode*constructUtil(vector<vector<int>>&mat,inti,intj){// Base case: if we are out of bounds, return NULLif(i>=mat.size()||j>=mat[0].size()){returnnullptr;}// Create a new Node with the current matrix valueNode*curr=newNode(mat[i][j]);// Recursively construct the right and down pointerscurr->right=constructUtil(mat,i,j+1);curr->down=constructUtil(mat,i+1,j);// Return the constructed Nodereturncurr;}// Function to construct the linked matrix given a 2D vectorNode*constructLinkedMatrix(vector<vector<int>>&mat){// Call the utility function starting // from the top-left corner of the matrixreturnconstructUtil(mat,0,0);}voidprintList(Node*head){Node*currRow=head;while(currRow!=nullptr){Node*currCol=currRow;while(currCol!=nullptr){cout<<currCol->data<<" ";currCol=currCol->right;}cout<<endl;currRow=currRow->down;}}intmain(){vector<vector<int>>mat={{1,2,3},{4,5,6},{7,8,9}};Node*head=constructLinkedMatrix(mat);printList(head);return0;}
Java
// Java to implement linked matrix // from a 2D matrix recursively importjava.util.ArrayList;classNode{intdata;Noderight,down;Node(intdata){this.data=data;this.right=null;this.down=null;}}classGfG{// Function to recursively construct the linked// matrix from a given 2D arraystaticNodeconstructUtil(int[][]arr,inti,intj){// Base case: if we are out of bounds, return nullif(i>=arr.length||j>=arr[0].length){returnnull;}// Create a new Node with the current// matrix valueNodecurr=newNode(arr[i][j]);// Recursively construct the right// and down pointerscurr.right=constructUtil(arr,i,j+1);curr.down=constructUtil(arr,i+1,j);// Return the constructed Nodereturncurr;}// Function to construct the linked // matrix given a 2D arraystaticNodeconstruct(intarr[][]){// Call the utility function starting from the // top-left corner of the matrixreturnconstructUtil(arr,0,0);}staticvoidprintList(Nodehead){NodecurrRow=head;while(currRow!=null){NodecurrCol=currRow;while(currCol!=null){System.out.print(currCol.data+" ");currCol=currCol.right;}System.out.println();currRow=currRow.down;}}publicstaticvoidmain(String[]args){intarr[][]={{1,2,3},{4,5,6},{7,8,9}};Nodehead=construct(arr);printList(head);}}
Python
# Python to implement linked matrix # from a 2D matrix recursively classNode:def__init__(self,data):self.data=dataself.right=Noneself.down=NonedefconstructUtil(mat,i,j):# Base case: if we are out of bounds, return Noneifi>=len(mat)orj>=len(mat[0]):returnNone# Create a new Node with the current matrix valuecurr=Node(mat[i][j])# Recursively construct the right and down pointerscurr.right=constructUtil(mat,i,j+1)curr.down=constructUtil(mat,i+1,j)# Return the constructed NodereturncurrdefconstructLinkedMatrix(mat):# Call the utility function starting # from the top-left corner of the matrixreturnconstructUtil(mat,0,0)defprintList(head):currRow=headwhilecurrRow:currCol=currRowwhilecurrCol:print(currCol.data,end=" ")currCol=currCol.rightprint()currRow=currRow.downif__name__=="__main__":mat=[[1,2,3],[4,5,6],[7,8,9]]head=constructLinkedMatrix(mat)printList(head)
C#
// C# to implement linked matrix // from a 2D matrix recursively usingSystem;usingSystem.Collections.Generic;classNode{publicintdata;publicNoderight,down;publicNode(intx){data=x;right=down=null;}}classGfG{// Recursive utility function to construct // the linked matrix from a 2D ListstaticNodeConstructUtil(List<List<int>>arr,inti,intj){// Base case: if we are out of bounds, return nullif(i>=arr.Count||j>=arr[0].Count)returnnull;// Create a new Node with the current list valueNodecurr=newNode(arr[i][j]);// Recursively construct the right and // down pointerscurr.right=ConstructUtil(arr,i,j+1);curr.down=ConstructUtil(arr,i+1,j);// Return the constructed Nodereturncurr;}// Function to construct the linked matrix // from a List of ListsstaticNodeConstruct(List<List<int>>arr){// Call the utility function starting // from the top-left cornerreturnConstructUtil(arr,0,0);}staticvoidPrintList(Nodehead){NodecurrRow=head;while(currRow!=null){NodecurrCol=currRow;while(currCol!=null){Console.Write(currCol.data+" ");currCol=currCol.right;}Console.WriteLine();currRow=currRow.down;}}staticvoidMain(string[]args){List<List<int>>arr=newList<List<int>>{newList<int>{1,2,3},newList<int>{4,5,6},newList<int>{7,8,9}};Nodehead=Construct(arr);PrintList(head);}}
JavaScript
// Javascript to implement linked matrix // from a 2D matrix recursively classNode{constructor(data){this.data=data;this.right=null;this.down=null;}}// Recursive utility function to construct // the linked matrixfunctionconstructUtil(arr,i,j){// Base case: if out of bounds, return nullif(i>=arr.length||j>=arr[0].length){returnnull;}// Create a new Node with the current array valueconstcurr=newNode(arr[i][j]);// Recursively construct the right and down pointerscurr.right=constructUtil(arr,i,j+1);curr.down=constructUtil(arr,i+1,j);// Return the constructed Nodereturncurr;}// Function to construct the linked matrix from a 2D arrayfunctionconstructLinkedMatrix(arr){// Start from the top-left cornerreturnconstructUtil(arr,0,0);}functionprintList(head){letcurrRow=head;while(currRow!==null){letcurrCol=currRow;while(currCol!==null){console.log(currCol.data+" ");currCol=currCol.right;}console.log();currRow=currRow.down;}}constarr=[[1,2,3],[4,5,6],[7,8,9]];consthead=constructLinkedMatrix(arr);printList(head);
Output
1 2 3
4 5 6
7 8 9
Time complexity:O(n^2), since each element in the 2D matrix is visited once to create the corresponding node in the linked structure. Auxiliary space: O(n^2), due to the storage needed for each node in the linked matrix.
[Expected Approach - 2] Iterative Approach - O(n^2) Time and O(n^2) Space
The approach involves creating m linked lists, where m represents the number of rows in a given 2D matrix. Each node in these linked lists stores a reference to its right neighbor. The head pointers of each linked list are maintained in an array. After constructing the linked lists, we traverse through them and for each i-th and (i+1)-th list, we establish the down pointers of each node in i-th list to point to the corresponding node in (i+1)-th list. Please refer to Construct a linked list from 2D matrix (Iterative Approach) for implementation.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.