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
Follow the steps below to solve the problem:
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.
C++
#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*linkMatrix(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=linkMatrix(mat);printList(head);return0;}
Java
classNode{intdata;Noderight,down;Node(intdata){this.data=data;this.right=null;this.down=null;}}classGFG{staticNodeconstructUtil(int[][]mat,inti,intj){// Base case: if we are out of bounds, return nullif(i>=mat.length||j>=mat[0].length){returnnull;}// Create a new Node with the current// matrix valueNodecurr=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 arraystaticNodelinkMatrix(intmat[][]){// Call the utility function starting from the// top-left corner of the matrixreturnconstructUtil(mat,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){intmat[][]={{1,2,3},{4,5,6},{7,8,9}};Nodehead=linkMatrix(mat);printList(head);}}
Python
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 NodereturncurrdeflinkMatrix(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.down# Driver Codeif__name__=="__main__":mat=[[1,2,3],[4,5,6],[7,8,9]]head=linkMatrix(mat)printList(head)
C#
usingSystem;usingSystem.Collections.Generic;classNode{publicintdata;publicNoderight,down;publicNode(intx){data=x;right=down=null;}}classGFG{staticNodeconstructUtil(List<List<int>>mat,inti,intj){// Base case: if we are out of bounds, return nullif(i>=mat.Count||j>=mat[0].Count)returnnull;// Create a new Node with the current list valueNodecurr=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// from a List of ListsstaticNodelinkMatrix(List<List<int>>mat){// Call the utility function starting// from the top-left cornerreturnconstructUtil(mat,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>>mat=newList<List<int>>{newList<int>{1,2,3},newList<int>{4,5,6},newList<int>{7,8,9}};Nodehead=linkMatrix(mat);PrintList(head);}}
JavaScript
classNode{constructor(x){this.data=x;this.right=null;this.down=null;}}// Function to recursively construct the linked matrix// from a given 2D arrayfunctionconstructUtil(mat,i,j){// Base case: if we are out of bounds, return nullif(i>=mat.length||j>=mat[0].length){returnnull;}// Create a new Node with the current matrix valueconstcurr=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 arrayfunctionlinkMatrix(mat){// Call the utility function starting// from the top-left corner of the matrixreturnconstructUtil(mat,0,0);}functionprintList(head){letcurrRow=head;letres="";while(currRow!==null){letcurrCol=currRow;while(currCol!==null){res+=currCol.data+" ";currCol=currCol.right;}res+="\n";currRow=currRow.down;}console.log(res.trim());}// Driver Codeconstmat=[[1,2,3],[4,5,6],[7,8,9]];consthead=linkMatrix(mat);printList(head);
Output
1 2 3
4 5 6
7 8 9
Iterative Approach - O(n^2) Time and O(n^2) Space
The approach involves creating m linked lists. 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.
The idea is to create m linked lists (m = number of rows) whose each node stores its right node. The head pointers of each m linked lists are stored in an array of nodes.
Then, traverse m lists, for every ith and (i+1)th list, set the down pointers of each node of ith list to its corresponding node of (i+1)th list.
C++
#include<bits/stdc++.h>usingnamespacestd;classNode{public:intdata;Node*right,*down;Node(intx){data=x;right=down=nullptr;}};// Function to construct the linked matrix// from the given 2D matrix.Node*linkMatrix(vector<vector<int>>&mat){introws=mat.size();intcols=mat[0].size();// Stores the head node of each row.vector<Node*>rowHeads(rows,nullptr);// Stores the head of the complete linked matrix.Node*mainHead=nullptr;// Create a linked list for each row// using the right pointers.for(inti=0;i<rows;i++){Node*rowTail=nullptr;for(intj=0;j<cols;j++){Node*newNode=newNode(mat[i][j]);// Set the first node as the main head.if(mainHead==nullptr){mainHead=newNode;}// Set the first node of the current row.if(rowHeads[i]==nullptr){rowHeads[i]=newNode;}else{// Link the current node using the right pointer.rowTail->right=newNode;}// Update the tail of the current row.rowTail=newNode;}}// Connect corresponding nodes of consecutive rows// using the down pointers.for(inti=0;i<rows-1;i++){Node*currentRow=rowHeads[i];Node*nextRow=rowHeads[i+1];while(currentRow!=nullptr&&nextRow!=nullptr){currentRow->down=nextRow;currentRow=currentRow->right;nextRow=nextRow->right;}}// Return the top-left node.returnmainHead;}// Function to print the linked matrix.voidprintList(Node*head){Node*currentRow=head;while(currentRow!=nullptr){Node*currentNode=currentRow;while(currentNode!=nullptr){cout<<currentNode->data<<" ";currentNode=currentNode->right;}cout<<endl;currentRow=currentRow->down;}}intmain(){vector<vector<int>>mat={{1,2,3},{4,5,6},{7,8,9}};Node*head=linkMatrix(mat);printList(head);return0;}
Java
classNode{intdata;Noderight,down;Node(intx){data=x;right=down=null;}}classGFG{// Function to construct the linked matrix// from the given 2D matrix.staticNodelinkMatrix(int[][]mat){introws=mat.length;intcols=mat[0].length;// Stores the head node of each row.Node[]rowHeads=newNode[rows];// Stores the head of the complete linked matrix.NodemainHead=null;// Create a linked list for each row// using the right pointers.for(inti=0;i<rows;i++){NoderowTail=null;for(intj=0;j<cols;j++){NodenewNode=newNode(mat[i][j]);// Set the first node as the main head.if(mainHead==null){mainHead=newNode;}// Set the first node of the current row.if(rowHeads[i]==null){rowHeads[i]=newNode;}else{// Link the current node using the right// pointer.rowTail.right=newNode;}// Update the tail of the current row.rowTail=newNode;}}// Connect corresponding nodes of consecutive rows// using the down pointers.for(inti=0;i<rows-1;i++){NodecurrentRow=rowHeads[i];NodenextRow=rowHeads[i+1];while(currentRow!=null&&nextRow!=null){currentRow.down=nextRow;currentRow=currentRow.right;nextRow=nextRow.right;}}// Return the top-left node.returnmainHead;}// Function to print the linked matrix.staticvoidprintList(Nodehead){NodecurrentRow=head;while(currentRow!=null){NodecurrentNode=currentRow;while(currentNode!=null){System.out.print(currentNode.data+" ");currentNode=currentNode.right;}System.out.println();currentRow=currentRow.down;}}publicstaticvoidmain(String[]args){int[][]mat={{1,2,3},{4,5,6},{7,8,9}};Nodehead=linkMatrix(mat);printList(head);}}
Python
classNode:def__init__(self,x):self.data=xself.right=Noneself.down=None# Function to construct the linked matrix# from the given 2D matrix.deflinkMatrix(mat):rows=len(mat)cols=len(mat[0])# Stores the head node of each row.rowHeads=[None]*rows# Stores the head of the complete linked matrix.mainHead=None# Create a linked list for each row# using the right pointers.foriinrange(rows):rowTail=Noneforjinrange(cols):newNode=Node(mat[i][j])# Set the first node as the main head.ifmainHeadisNone:mainHead=newNode# Set the first node of the current row.ifrowHeads[i]isNone:rowHeads[i]=newNodeelse:# Link the current node using the right pointer.rowTail.right=newNode# Update the tail of the current row.rowTail=newNode# Connect corresponding nodes of consecutive rows# using the down pointers.foriinrange(rows-1):currentRow=rowHeads[i]nextRow=rowHeads[i+1]whilecurrentRowisnotNoneandnextRowisnotNone:currentRow.down=nextRowcurrentRow=currentRow.rightnextRow=nextRow.right# Return the top-left node.returnmainHead# Function to print the linked matrix.defprintList(head):currentRow=headwhilecurrentRowisnotNone:currentNode=currentRowwhilecurrentNodeisnotNone:print(currentNode.data,end=" ")currentNode=currentNode.rightprint()currentRow=currentRow.down# Driver Codeif__name__=="__main__":mat=[[1,2,3],[4,5,6],[7,8,9]]head=linkMatrix(mat)printList(head)
C#
usingSystem;usingSystem.Collections.Generic;classNode{publicintdata;publicNoderight,down;publicNode(intx){data=x;right=down=null;}}classGFG{// Function to construct the linked matrix// from the given 2D matrix.staticNodelinkMatrix(List<List<int>>mat){introws=mat.Count;intcols=mat[0].Count;// Stores the head node of each row.List<Node>rowHeads=newList<Node>(newNode[rows]);// Stores the head of the complete linked matrix.NodemainHead=null;// Create a linked list for each row// using the right pointers.for(inti=0;i<rows;i++){NoderowTail=null;for(intj=0;j<cols;j++){NodenewNode=newNode(mat[i][j]);// Set the first node as the main head.if(mainHead==null){mainHead=newNode;}// Set the first node of the current row.if(rowHeads[i]==null){rowHeads[i]=newNode;}else{// Link the current node using the right// pointer.rowTail.right=newNode;}// Update the tail of the current row.rowTail=newNode;}}// Connect corresponding nodes of consecutive rows// using the down pointers.for(inti=0;i<rows-1;i++){NodecurrentRow=rowHeads[i];NodenextRow=rowHeads[i+1];while(currentRow!=null&&nextRow!=null){currentRow.down=nextRow;currentRow=currentRow.right;nextRow=nextRow.right;}}// Return the top-left node.returnmainHead;}// Function to print the linked matrix.staticvoidprintList(Nodehead){NodecurrentRow=head;while(currentRow!=null){NodecurrentNode=currentRow;while(currentNode!=null){Console.Write(currentNode.data+" ");currentNode=currentNode.right;}Console.WriteLine();currentRow=currentRow.down;}}staticvoidMain(){List<List<int>>mat=newList<List<int>>{newList<int>{1,2,3},newList<int>{4,5,6},newList<int>{7,8,9}};Nodehead=linkMatrix(mat);printList(head);}}
JavaScript
classNode{constructor(x){this.data=x;this.right=null;this.down=null;}}// Function to construct the linked matrix// from the given 2D matrix.functionlinkMatrix(mat){constrows=mat.length;constcols=mat[0].length;// Stores the head node of each row.constrowHeads=newArray(rows).fill(null);// Stores the head of the complete linked matrix.letmainHead=null;// Create a linked list for each row// using the right pointers.for(leti=0;i<rows;i++){letrowTail=null;for(letj=0;j<cols;j++){constnewNode=newNode(mat[i][j]);// Set the first node as the main head.if(mainHead===null){mainHead=newNode;}// Set the first node of the current row.if(rowHeads[i]===null){rowHeads[i]=newNode;}else{// Link the current node using the right// pointer.rowTail.right=newNode;}// Update the tail of the current row.rowTail=newNode;}}// Connect corresponding nodes of consecutive rows// using the down pointers.for(leti=0;i<rows-1;i++){letcurrentRow=rowHeads[i];letnextRow=rowHeads[i+1];while(currentRow!==null&&nextRow!==null){currentRow.down=nextRow;currentRow=currentRow.right;nextRow=nextRow.right;}}// Return the top-left node.returnmainHead;}// Function to print the linked matrix.functionprintList(head){letcurrentRow=head;while(currentRow!==null){letcurrentNode=currentRow;while(currentNode!==null){process.stdout.write(currentNode.data+" ");currentNode=currentNode.right;}console.log();currentRow=currentRow.down;}}// Driver Codeconstmat=[[1,2,3],[4,5,6],[7,8,9]];consthead=linkMatrix(mat);printList(head);