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++

Java

Python3

C#

Javascript



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++

Java

Python3

C#

Javascript



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.

Previous
Next