# Construct a linked list from 2D matrix

• Difficulty Level : Medium
• Last Updated : 06 May, 2022

Given a matrix. Convert it into a linked list matrix such that each node is connected to its next right and down node.
Example:

Input : 2D matrix
1 2 3
4 5 6
7 8 9
Output :
1 -> 2 -> 3 -> NULL
|        |     |
v       v    v
4 -> 5 -> 6 -> NULL
|        |     |
v      v     v
7 -> 8 -> 9 -> NULL
|       |       |
v     v       v
NULL NULL NULL

Question Source: Factset Interview Experience | Set 9

Approach: The problem can be solved based on the following idea:

Connect every cell to its right cell of the same row and to its bottom cell in the same column and also for each cell and keep track of those created node.

Follow the steps mentioned below to solve this problem:

• First create a variable of Node type, which will store address of its right and bottom Node corresponding to cell in the matrix.
• Recursively do the following steps for any cell in the matrix:
• If Node is not created for any corresponding cell in the matrix, then create a new Node and store it.
• Else we reach at some cell which has already been created for its corresponding cell in the matrix then return that stored Node.
• Attach Node to its right and bottom cell which is created and return the current Node.
• Finally return the root Node.

Below is the implementation of the above approach:

## C++

 `// CPP program to construct a linked list` `// from given 2D matrix` `#include ` `using` `namespace` `std;`   `// struct node of linked list` `struct` `Node {` `    ``int` `data;` `    ``Node* right, *down;` `};`   `// returns head pointer of linked list` `// constructed from 2D matrix` `Node* construct(``int` `arr[], ``int` `i, ``int` `j,` `                            ``int` `m, ``int` `n, vector> &visited)` `{` `    ``// return if i or j is out of bounds` `    ``if` `(i > m - 1 || j > n - 1)` `        ``return` `NULL;`   `      ``// Check if node is previously created then,` `      ``// don't need to create new/` `    ``if``(visited[i][j]){` `        ``return` `visited[i][j];` `    ``} `   `    ``// create a new node for current i and j` `    ``// and recursively allocate its down and` `    ``// right pointers` `    ``Node* temp = ``new` `Node();` `    ``visited[i][j] = temp;` `    ``temp->data = arr[i][j];` `    ``temp->right = construct(arr, i, j + 1, m, n, visited);` `    ``temp->down = construct(arr, i + 1, j, m, n, visited);` `    ``return` `temp;` `}`   `// utility function for displaying` `// linked list data` `void` `display(Node* head)` `{` `    ``// pointer to move right` `    ``Node* Rp;`   `    ``// pointer to move down` `    ``Node* Dp = head;`   `    ``// loop till node->down is not NULL` `    ``while` `(Dp) {` `        ``Rp = Dp;`   `        ``// loop till node->right is not NULL` `        ``while` `(Rp) {` `            ``cout << Rp->data << ``" "``;` `            ``Rp = Rp->right;` `        ``}` `        ``cout << ``"\n"``;` `        ``Dp = Dp->down;` `    ``}` `}`   `// driver program` `int` `main()` `{` `    ``// 2D matrix` `    ``int` `arr[] = {` `        ``{ 1, 2, 3, 0},` `        ``{ 4, 5, 6 , 1},` `        ``{ 7, 8, 9 , 2},` `        ``{ 7, 8, 9 , 2}` `    ``};`     `    ``int` `m = 4, n = 4;` `    ``vector> visited(m, vector(n));` `  `  `    ``Node* head = construct(arr, 0, 0, m, n, visited);` `    ``display(head);` `  `  `    ``return` `0;` `}`

## Java

 `// Java program to construct a linked list` `// from given 2D matrix` `public` `class` `Linked_list_2D_Matrix {`   `    ``// node of linked list` `    ``static` `class` `Node {` `        ``int` `data;` `        ``Node right;` `        ``Node down;` `    ``};`   `    ``// returns head pointer of linked list` `    ``// constructed from 2D matrix` `    ``static` `Node construct(``int` `arr[][], ``int` `i, ``int` `j, ` `                                     ``int` `m, ``int` `n, Node[][] visited) {` `        `  `        ``// return if i or j is out of bounds` `        ``if` `(i > m - ``1` `|| j > n - ``1``)` `            ``return` `null``;` `      `  `      ``// Check if node is previously created then,` `      ``// don't need to create new/` `      ``if``(visited[i][j] != ``null``){` `          ``return` `visited[i][j];` `      ``} `   `        ``// create a new node for current i and j` `        ``// and recursively allocate its down and` `        ``// right pointers` `        ``Node temp = ``new` `Node();` `          ``visited[i][j] = temp;` `        ``temp.data = arr[i][j];` `        ``temp.right = construct(arr, i, j + ``1``, m, n, visited);` `        ``temp.down = construct(arr, i + ``1``, j, m, n, visited);` `        ``return` `temp;` `    ``}`   `    ``// utility function for displaying` `    ``// linked list data` `    ``static` `void` `display(Node head) {` `        `  `        ``// pointer to move right` `        ``Node Rp;`   `        ``// pointer to move down` `        ``Node Dp = head;`   `        ``// loop till node->down is not NULL` `        ``while` `(Dp != ``null``) {` `            ``Rp = Dp;`   `            ``// loop till node->right is not NULL` `            ``while` `(Rp != ``null``) {` `                ``System.out.print(Rp.data + ``" "``);` `                ``Rp = Rp.right;` `            ``}` `            ``System.out.println();` `            ``Dp = Dp.down;` `        ``}` `    ``}`   `    ``// driver program` `    ``public` `static` `void` `main(String args[]) {` `        ``// 2D matrix` `        ``int` `arr[][] = {` `            ``{ ``1``, ``2``, ``3``, ``0``},` `            ``{ ``4``, ``5``, ``6` `, ``1``},` `            ``{ ``7``, ``8``, ``9` `, ``2``},` `            ``{ ``7``, ``8``, ``9` `, ``2``}` `        ``};`   `        ``int` `m = ``4``, n = ``4``;` `      `  `        ``// List> arr = new ArrayList>();` `          ``Node[][] visited = ``new` `Node[m][n];` `          `  `        ``Node head = construct(arr, ``0``, ``0``, m, n, visited);` `        ``display(head);` `    ``}`   `}` `// This code is contributed by Sumit Ghosh`

Output

```1 2 3 0
4 5 6 1
7 8 9 2
7 8 9 2
```

Time complexity: O(N*M), where N is the number of row and M is the number of column.
Auxiliary space: O(N*M)

This article is contributed by Mandeep Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.