Given a 2D matrix, the task is to convert it into a doubly-linked list with four pointers that are next, previous, up, and down, each node of this list should be connected to its next, previous, up, and down nodes.
Examples:
Input: 2D matrix
1 2 3
4 5 6
7 8 9
Output:

Approach: The main idea is to construct a new node for every element of the matrix and recursively create it’s up, down, previous and next nodes and change the pointer of previous and up pointers respectively.
Below is the implementation of the above approach:
C++
#include <iostream>
using namespace std;
#define dim 3
struct Node {
int data;
Node* next;
Node* prev;
Node* up;
Node* down;
};
Node* createNode( int data)
{
Node* temp = new Node();
temp->data = data;
temp->next = NULL;
temp->prev = NULL;
temp->up = NULL;
temp->down = NULL;
return temp;
}
Node* constructDoublyListUtil(
int mtrx[][dim],
int i, int j,
Node* curr)
{
if (i >= dim || j >= dim) {
return NULL;
}
Node* temp = createNode(mtrx[i][j]);
temp->prev = curr;
temp->up = curr;
temp->next
= constructDoublyListUtil(
mtrx, i, j + 1, temp);
temp->down
= constructDoublyListUtil(
mtrx, i + 1, j, temp);
return temp;
}
Node* constructDoublyList( int mtrx[][dim])
{
return constructDoublyListUtil(
mtrx, 0, 0, NULL);
}
void display(Node* head)
{
Node* rPtr;
Node* dPtr = head;
while (dPtr) {
rPtr = dPtr;
while (rPtr) {
cout << rPtr->data << " " ;
rPtr = rPtr->next;
}
cout << "\n" ;
dPtr = dPtr->down;
}
}
int main()
{
int mtrx[dim][dim] = {
{ 1, 2, 3 },
{ 4, 5, 6 },
{ 7, 8, 9 }
};
Node* list = constructDoublyList(mtrx);
display(list);
return 0;
}
|
Java
import java.util.*;
class GFG{
static int dim= 3 ;
static class Node {
int data;
Node next;
Node prev;
Node up;
Node down;
};
static Node createNode( int data)
{
Node temp = new Node();
temp.data = data;
temp.next = null ;
temp.prev = null ;
temp.up = null ;
temp.down = null ;
return temp;
}
static Node constructDoublyListUtil( int mtrx[][], int i, int j,Node curr)
{
if (i >= dim || j >= dim) {
return null ;
}
Node temp = createNode(mtrx[i][j]);
temp.prev = curr;
temp.up = curr;
temp.next
= constructDoublyListUtil(mtrx, i, j + 1 , temp);
temp.down= constructDoublyListUtil(mtrx, i + 1 , j, temp);
return temp;
}
static Node constructDoublyList( int mtrx[][])
{
return constructDoublyListUtil(mtrx, 0 , 0 , null );
}
static void display(Node head)
{
Node rPtr;
Node dPtr = head;
while (dPtr != null ) {
rPtr = dPtr;
while (rPtr!= null ) {
System.out.print(rPtr.data+ " " );
rPtr = rPtr.next;
}
System.out.print( "\n" );
dPtr = dPtr.down;
}
}
public static void main(String args[])
{
int mtrx[][] = {
{ 1 , 2 , 3 },
{ 4 , 5 , 6 },
{ 7 , 8 , 9 }
};
Node list = constructDoublyList(mtrx);
display(list);
}
}
|
Python3
dim = 3
class Node:
def __init__( self , data):
self .data = data
self .prev = None
self .up = None
self .down = None
self . next = None
def createNode(data):
temp = Node(data);
return temp;
def constructDoublyListUtil(mtrx, i,
j, curr):
if (i > = dim or
j > = dim):
return None ;
temp = createNode(mtrx[i][j]);
temp.prev = curr;
temp.up = curr;
temp. next = constructDoublyListUtil(mtrx, i,
j + 1 ,
temp);
temp.down = constructDoublyListUtil(mtrx,
i + 1 ,
j, temp);
return temp;
def constructDoublyList(mtrx):
return constructDoublyListUtil(mtrx,
0 , 0 ,
None );
def display(head):
rPtr = None
dPtr = head;
while (dPtr ! = None ):
rPtr = dPtr;
while (rPtr ! = None ):
print (rPtr.data,
end = ' ' )
rPtr = rPtr. next ;
print ()
dPtr = dPtr.down;
if __name__ = = "__main__" :
mtrx = [[ 1 , 2 , 3 ],
[ 4 , 5 , 6 ],
[ 7 , 8 , 9 ]]
list = constructDoublyList(mtrx);
display( list );
|
C#
using System;
class GFG{
static int dim= 3;
public class Node {
public int data;
public Node next, prev, up, down;
};
static Node createNode( int data)
{
Node temp = new Node();
temp.data = data;
temp.next = null ;
temp.prev = null ;
temp.up = null ;
temp.down = null ;
return temp;
}
static Node constructDoublyListUtil( int [,] mtrx, int i, int j,Node curr)
{
if (i >= dim || j >= dim) {
return null ;
}
Node temp = createNode(mtrx[i,j]);
temp.prev = curr;
temp.up = curr;
temp.next
= constructDoublyListUtil(mtrx, i, j + 1, temp);
temp.down= constructDoublyListUtil(mtrx, i + 1, j, temp);
return temp;
}
static Node constructDoublyList( int [,] mtrx)
{
return constructDoublyListUtil(mtrx, 0, 0, null );
}
static void display(Node head)
{
Node rPtr;
Node dPtr = head;
while (dPtr != null ) {
rPtr = dPtr;
while (rPtr!= null ) {
Console.Write(rPtr.data+ " " );
rPtr = rPtr.next;
}
Console.Write( "\n" );
dPtr = dPtr.down;
}
}
public static void Main()
{
int [,] mtrx = {
{ 1, 2, 3 },
{ 4, 5, 6 },
{ 7, 8, 9 }
};
Node list = constructDoublyList(mtrx);
display(list);
}
}
|
Javascript
<script>
var dim = 3;
class Node
{
constructor()
{
this .data = 0;
this .next = null ;
this .prev = null ;
this .up = null ;
this .down = null ;
}
}
function createNode(data)
{
temp = new Node();
temp.data = data;
temp.next = null ;
temp.prev = null ;
temp.up = null ;
temp.down = null ;
return temp;
}
function constructDoublyListUtil(mtrx, i , j, curr)
{
if (i >= dim || j >= dim) {
return null ;
}
var temp = createNode(mtrx[i][j]);
temp.prev = curr;
temp.up = curr;
temp.next
= constructDoublyListUtil(mtrx, i, j + 1, temp);
temp.down= constructDoublyListUtil(mtrx, i + 1, j, temp);
return temp;
}
function constructDoublyList(mtrx)
{
return constructDoublyListUtil(mtrx, 0, 0, null );
}
function display( head)
{
rPtr = null ;
dPtr = head;
while (dPtr != null ) {
rPtr = dPtr;
while (rPtr != null )
{
document.write(rPtr.data + " " );
rPtr = rPtr.next;
}
document.write( "<br/>" );
dPtr = dPtr.down;
}
}
var mtrx = [
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
];
var list = constructDoublyList(mtrx);
display(list);
</script>
|
Output:
1 2 3
4 5 6
7 8 9
Time Complexity: O(N*M)
Auxiliary Space: O(N*M) due to recursion
Method 2 – Iterative Approach
We will make use of dummy nodes to mark the start of up and prev pointers. Also in the above approach, we are creating so many extra nodes, here we will not be creating many extra nodes.
This approach performs better in the case of a large 2D Matrix, as it does not gets overhead recursion calls.
C++
#include<bits/stdc++.h>
using namespace std;
struct Node {
int data;
Node* left;
Node* right;
Node* up;
Node* down;
Node( int x) : data(x) , left(NULL) , right(NULL) , up(NULL) , down(NULL) {}
};
void print(Node* head) {
Node* downptr = head;
Node* rightptr;
while (downptr) {
rightptr = downptr;
while (rightptr) {
cout << (rightptr->data) << " " ;
rightptr = rightptr->right;
}
cout << "\n" ;
downptr = downptr->down;
}
}
int main() {
int mat[3][3] = {
{ 1, 2, 3 },
{ 4, 5, 6 },
{ 7, 8, 9 }
};
int n = 3, m = 3;
Node* head_main = NULL;
Node* prev, *upper = new Node(-1);
for ( int i = 0; i < n; i++) {
Node* head_row;
Node *prev = new Node(-1);
for ( int j = 0; j < m; j++) {
Node* temp = new Node(mat[i][j]);
if (j == 0) head_row = temp;
if (i == 0 && j == 0) head_main = temp;
temp->left = prev;
prev->right = temp;
if (i == n - 1) temp->down = NULL;
if (!upper->right) {
upper->right = new Node(-1);
}
upper = upper->right;
temp->up = upper;
upper->down = temp;
prev = temp;
if (j == m - 1) prev->right = NULL;
}
upper = head_row->left;
}
print(head_main);
return 0;
}
|
Java
import java.util.*;
public class Main {
static class Node {
int data;
Node left;
Node right;
Node up;
Node down;
Node( int x)
{
data = x;
left = null ;
right = null ;
up = null ;
down = null ;
}
}
public static void print(Node head)
{
Node downptr = head;
Node rightptr;
while (downptr != null ) {
rightptr = downptr;
while (rightptr != null ) {
System.out.print(rightptr.data + " " );
rightptr = rightptr.right;
}
System.out.println();
downptr = downptr.down;
}
}
public static void main(String[] args)
{
int [][] mat
= { { 1 , 2 , 3 }, { 4 , 5 , 6 }, { 7 , 8 , 9 } };
int n = 3 , m = 3 ;
Node head_main
= null ;
Node prev, upper
= new Node(- 1 );
for ( int i = 0 ; i < n; i++) {
Node head_row
= new Node(- 1 );
prev = new Node(- 1 );
for ( int j = 0 ; j < m; j++) {
Node temp = new Node(mat[i][j]);
if (j == 0 )
head_row = temp;
if (i == 0 && j == 0 )
head_main = temp;
temp.left = prev;
prev.right = temp;
if (i == n - 1 )
temp.down = null ;
if (upper.right == null )
upper.right = new Node(- 1 );
upper = upper.right;
temp.up = upper;
upper.down = temp;
prev = temp;
if (j == m - 1 )
prev.right = null ;
}
upper = head_row.left;
}
print(head_main);
}
}
|
Python3
class Node:
def __init__( self , data):
self .data = data
self .left = None
self .right = None
self .up = None
self .down = None
def printList(head):
downptr = head
rightptr = None
while downptr ! = None :
rightptr = downptr
while rightptr ! = None :
print (rightptr.data, end = " " )
rightptr = rightptr.right
print ()
downptr = downptr.down
if __name__ = = "__main__" :
mat = [
[ 1 , 2 , 3 ],
[ 4 , 5 , 6 ],
[ 7 , 8 , 9 ]
]
n = 3
m = 3
head_main = None
prev = None
upper = Node( - 1 )
for i in range (n):
head_row = None
prev = Node( - 1 )
for j in range (m):
temp = Node(mat[i][j])
if j = = 0 :
head_row = temp
if i = = 0 and j = = 0 :
head_main = temp
temp.left = prev
prev.right = temp
if i = = n - 1 :
temp.down = None
if upper.right = = None :
upper.right = Node( - 1 )
upper = upper.right
temp.up = upper
upper.down = temp
prev = temp
if j = = m - 1 :
prev.right = None
upper = head_row.left
printList(head_main)
|
C#
using System;
class Program {
static void Main( string [] args)
{
int [, ] mat
= { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
int n = 3, m = 3;
Node head_main
= null ;
Node prev, upper
= new Node(-1);
for ( int i = 0; i < n; i++) {
Node head_row
= new Node(-1);
prev = new Node(-1);
for ( int j = 0; j < m; j++) {
Node temp = new Node(mat[i, j]);
if (j == 0)
head_row = temp;
if (i == 0 && j == 0)
head_main = temp;
temp.left = prev;
prev.right = temp;
if (i == n - 1)
temp.down = null ;
if (upper.right == null )
upper.right = new Node(-1);
upper = upper.right;
temp.up = upper;
upper.down = temp;
prev = temp;
if (j == m - 1)
prev.right = null ;
}
upper = head_row.left;
}
print(head_main);
}
public static void print(Node head)
{
Node downptr = head;
Node rightptr;
while (downptr != null ) {
rightptr = downptr;
while (rightptr != null ) {
Console.Write(rightptr.data + " " );
rightptr = rightptr.right;
}
Console.WriteLine();
downptr = downptr.down;
}
}
}
class Node {
public int data;
public Node left;
public Node right;
public Node up;
public Node down;
public Node( int x)
{
data = x;
left = null ;
right = null ;
up = null ;
down = null ;
}
}
|
Javascript
<script>
class Node {
constructor(x)
{
this .data = x;
this .left = null ;
this .right = null ;
this .up = null ;
this .down = null ;
}
}
function print(head)
{
let downptr = head;
let rightptr;
while (downptr) {
rightptr = downptr;
while (rightptr) {
document.write(rightptr.data, " " );
rightptr = rightptr.right;
}
document.write( "</br>" );
downptr = downptr.down;
}
}
let mat = [
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
];
let n = 3, m = 3;
let head_main = null ;
let prev, upper = new Node(-1);
for (let i = 0; i < n; i++) {
let head_row;
let prev = new Node(-1);
for (let j = 0; j < m; j++) {
let temp = new Node(mat[i][j]);
if (j == 0) head_row = temp;
if (i == 0 && j == 0) head_main = temp;
temp.left = prev;
prev.right = temp;
if (i == n - 1) temp.down = null ;
if (!upper.right) {
upper.right = new Node(-1);
}
upper = upper.right;
temp.up = upper;
upper.down = temp;
prev = temp;
if (j == m - 1) prev.right = null ;
}
upper = head_row.left;
}
print(head_main)
</script>
|
Output:
1 2 3
4 5 6
7 8 9
Time Complexity: O(n*m) where n represents the number of rows, m represents the number of columns in our matrix.
Space Complexity: O(1) constant extra space.
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
23 Jan, 2023
Like Article
Save Article