Given a matrix mat of size n × n, construct a 2D linked list that represents the matrix, where each node stores the value of a cell and contains pointers to its right and down neighbors.
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*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
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
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#
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
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
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++
// C++ to implement linked matrix // from a 2D matrix iteratively #include<bits/stdc++.h>usingnamespacestd;classNode{public:intdata;Node*right,*down;Node(intx){data=x;right=down=nullptr;}};// Function to construct the linked list from the given/// matrix and return the head pointerNode*constructLinkedMatrix(vector<vector<int>>&mat){intm=mat.size();intn=mat[0].size();// Stores the head of the linked listNode*mainhead=nullptr;// Stores the head of linked lists of each rowvector<Node*>head(m);Node*rightcurr,*newptr;// Create m linked lists by setting all // the right nodes of every rowfor(inti=0;i<m;i++){head[i]=nullptr;for(intj=0;j<n;j++){newptr=newNode(mat[i][j]);// Assign the first node as the mainheadif(!mainhead){mainhead=newptr;}// Set the head for the row or link // the current nodeif(!head[i]){head[i]=newptr;}else{rightcurr->right=newptr;}rightcurr=newptr;}}// Set the down pointers for nodes in consecutive rowsfor(inti=0;i<m-1;i++){Node*curr1=head[i],*curr2=head[i+1];// Link corresponding nodes in consecutive rowswhile(curr1&&curr2){curr1->down=curr2;curr1=curr1->right;curr2=curr2->right;}}// Return the mainhead of the constructed // linked listreturnmainhead;}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 iteratively importjava.util.ArrayList;classNode{intdata;Noderight,down;Node(intdata){this.data=data;this.right=null;this.down=null;}}classGfG{// Function to construct the linked // matrix from a 2D arraystaticNodeconstruct(intarr[][]){intm=arr.length;intn=arr[0].length;// Stores the head of the linked listNodemainhead=null;// ArrayList to store the heads of // linked lists for each rowArrayList<Node>head=newArrayList<>(m);Noderightcurr=null;// Create m linked lists by setting all// the right nodes of every rowfor(inti=0;i<m;i++){head.add(null);for(intj=0;j<n;j++){Nodenewptr=newNode(arr[i][j]);// Assign the first node as the mainheadif(mainhead==null){mainhead=newptr;}// Set the head for the row or link // the current nodeif(head.get(i)==null){head.set(i,newptr);}else{rightcurr.right=newptr;}rightcurr=newptr;}}// Set the down pointers for nodes in // consecutive rowsfor(inti=0;i<m-1;i++){Nodecurr1=head.get(i);Nodecurr2=head.get(i+1);// Link corresponding nodes in consecutive rowswhile(curr1!=null&&curr2!=null){curr1.down=curr2;curr1=curr1.right;curr2=curr2.right;}}// Return the mainhead of the constructed // linked listreturnmainhead;}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 iteratively classNode:def__init__(self,data):self.data=dataself.right=Noneself.down=NonedefconstructLinkedMatrix(mat):m=len(mat)n=len(mat[0])# Stores the head of the linked listmainhead=None# Stores the head of linked lists of each rowhead=[None]*mrightcurr=None# Create m linked lists by setting all the # right nodes of every rowforiinrange(m):head[i]=Noneforjinrange(n):newptr=Node(mat[i][j])# Assign the first node as the mainheadifnotmainhead:mainhead=newptr# Set the head for the row or link the # current nodeifnothead[i]:head[i]=newptrelse:rightcurr.right=newptrrightcurr=newptr# Set the down pointers for nodes in consecutive rowsforiinrange(m-1):curr1=head[i]curr2=head[i+1]# Link corresponding nodes in consecutive rowswhilecurr1andcurr2:curr1.down=curr2curr1=curr1.rightcurr2=curr2.right# Return the mainhead of the constructed linked listreturnmainheaddefprintList(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 iteratively usingSystem;usingSystem.Collections.Generic;classNode{publicintdata;publicNoderight,down;publicNode(intx){data=x;right=down=null;}}classGfG{// Function to construct the linked matrix // from a List of ListsstaticNodeConstruct(List<List<int>>arr){intm=arr.Count;intn=arr[0].Count;// Stores the head of the linked listNodemainhead=null;// List to store the heads of linked // lists for each rowList<Node>head=newList<Node>(m);Noderightcurr=null;// Create m linked lists by setting all the // right nodes of every rowfor(inti=0;i<m;i++){head.Add(null);for(intj=0;j<n;j++){Nodenewptr=newNode(arr[i][j]);// Assign the first node as the mainheadif(mainhead==null){mainhead=newptr;}// Set the head for the row or link // the current nodeif(head[i]==null){head[i]=newptr;}else{rightcurr.right=newptr;}rightcurr=newptr;}}// Set the down pointers for nodes // in consecutive rowsfor(inti=0;i<m-1;i++){Nodecurr1=head[i];Nodecurr2=head[i+1];// Link corresponding nodes in // consecutive rowswhile(curr1!=null&&curr2!=null){curr1.down=curr2;curr1=curr1.right;curr2=curr2.right;}}// Return the mainhead of the // constructed linked listreturnmainhead;}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 iteratively classNode{constructor(data){this.data=data;this.right=null;this.down=null;}}// Function to construct the linked matrix // from a 2D arrayfunctionconstructLinkedMatrix(arr){constm=arr.length;constn=arr[0].length;// Stores the head of the linked listletmainHead=null;// Array to store the heads of linked // lists for each rowconsthead=newArray(m).fill(null);letrightCurr=null;// Create m linked lists by setting all the // right nodes of every rowfor(leti=0;i<m;i++){for(letj=0;j<n;j++){constnewPtr=newNode(arr[i][j]);// Assign the first node as the mainHeadif(mainHead===null){mainHead=newPtr;}// Set the head for the row or // link the current nodeif(head[i]===null){head[i]=newPtr;}else{rightCurr.right=newPtr;}rightCurr=newPtr;}}// Set the down pointers for nodes in // consecutive rowsfor(leti=0;i<m-1;i++){letcurr1=head[i];letcurr2=head[i+1];// Link corresponding nodes in consecutive rowswhile(curr1&&curr2){curr1.down=curr2;curr1=curr1.right;curr2=curr2.right;}}// Return the mainHead of the constructed // linked listreturnmainHead;}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);