Open In App

Construct Linked List from 3D Matrix

Last Updated : 11 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Given a 3D matrix mat[ ][ ][ ] of size X * Y * Z. The task is to convert this matrix into a fully connected Cyclic linked list. Each node will have the 6 pointers namely: Left, Right, Up, Down, Front, Back.
Examples: 
 

Input: X = 2, Y = 2, Z = 2 
mat[0][0][0] = 10 mat[0][0][1] = 11 
mat[0][1][0] = 12 mat[0][1][1] = 13 
mat[1][0][0] = 14 mat[1][0][1] = 15 
mat[1][1][0] = 16 mat[1][1][1] = 17 
 

Output: 
element  front  back  left  right  up  down 
   10       14      14     11    11    12   12 
   11       15      15     10    10    13   13 
   12       16      16     13    13    10   10 
   13       17      17     12    12    11   11 
   14       10      10     15    15    16   16 
   15       11      11     14    14    17   17 
   16       12      12     17    17    14   14 
   17       13      13     16    16    15   15 
Explanation: 
For mat[0][0][0] having value 10: 
Its back pointer points to cell mat[1][0][0] having value 14. 
It doesn’t have any element in front of it. In order to maintain the cyclic order, the front pointer points to cell mat[1][0][0] having value 12. 
Its right pointer points to cell mat[0][0][1] having value 11. 
It doesn’t have any element to its left. In order to maintain the cyclic order, the left pointer points to cell mat[0][0][1] having value 11. 
Its bottom pointer points to cell mat[0][1][0] having value 12. 
It doesn’t have any element above it. In order to maintain the cyclic order, the top pointer points to cell mat[0][1][0] having value 12. 
In this way, all the pointers of each cell are connected to their respective cells. 
Input: X = 1, Y = 3, Z = 2 
mat[0][0][0] = 1 mat[0][0][1] = 2 mat[0][0][0] = 3
mat[0][1][0] = 4 mat[0][1][1] = 5 mat[0][0][0] = 6
Output: 
element  front  back   left  right  up  down 
   1           4       4        3      2      1      1 
   2           5       5        1      3      2      2 
   3           6       6        2      1      3      3 
   4           1       1        6      5      4      4 
   5           2       2        4      6      5      5
   6           3       3        5      4      6      6

Approach: 

  • For each cell of the matrix, create a node consisting of 6 pointers as Up, Down, Left, Right, Back and Front.
  • Link the Down pointers of all the nodes. For a given cell, if no cell exists below it, point its down pointer to the topmost cell of the row to maintain the cyclic order.
  • Link the Up pointers of all the nodes. For a given cell, if no cell exists above it, point its up pointer to the bottom-most cell of the row to maintain the cyclic order.
  • Link the Right pointer of all the nodes. For a given cell, if no cell exists to its right, point its right pointer to the leftmost cell of the row to maintain the cyclic order.
  • Link the Left pointer of all the nodes. For a given cell, if no cell exists to its left, point its left pointer to the rightmost cell of the row to maintain the cyclic order.
  • Link the Front pointer of all the nodes. For a given cell, if no cell exists in front of it, point its front pointer to the back-most cell of the row to maintain the cyclic order.
  • Link the Back pointer of all the nodes. For a given cell, if no cell exists behind it, point its back pointer to the front-most cell of the row to maintain the cyclic order.
  • Thus link all the pointers in a cyclic manner. Traverse the entire linked list so formed, and for each node of the linked list, print all the values that it points using its 6 pointers.

Below is the implementation of the above approach:
 

CPP




// C++ code for the above program
 
#include <bits/stdc++.h>
using namespace std;
 
// Node structure of the
// 3D-linked list
class ThreeDLinkedListNode {
public:
    int val;
    ThreeDLinkedListNode* front;
    ThreeDLinkedListNode* back;
    ThreeDLinkedListNode* up;
    ThreeDLinkedListNode* right;
    ThreeDLinkedListNode* down;
    ThreeDLinkedListNode* left;
 
    ThreeDLinkedListNode(
        int x,
        ThreeDLinkedListNode* f = NULL,
        ThreeDLinkedListNode* b = NULL,
        ThreeDLinkedListNode* u = NULL,
        ThreeDLinkedListNode* r = NULL,
        ThreeDLinkedListNode* d = NULL,
        ThreeDLinkedListNode* l = NULL)
    {
        // initialization of 3D
        // linkedlist Node
        val = x;
        front = f;
        back = b;
        up = u;
        right = r;
        down = d;
        left = l;
    }
 
    vector<int> extractNeighbors()
    {
        // extracting all front,
        // back, up, down, left,
        // right neighbours of
        // the node
        vector<int> neighbour;
 
        // front back left right up down
        neighbour.push_back(front->val);
        neighbour.push_back(back->val);
        neighbour.push_back(left->val);
        neighbour.push_back(right->val);
        neighbour.push_back(up->val);
        neighbour.push_back(down->val);
        return neighbour;
    }
};
 
class Solution {
public:
    void setDown(
        vector<vector<vector<int> > > a,
        int layer, int row, int column,
        ThreeDLinkedListNode* node)
    {
        // setting the down pointers
        // of all nodes in a
        // 3D linked list
        bool flag = false;
        ThreeDLinkedListNode* head = node;
 
        // loop to traverse the layers
        for (int i = 0;
             i < layer; i++) {
 
            ThreeDLinkedListNode*
                start_layer_head
                = node;
 
            // Loop to traverse the
            // columns of each layer
            for (int j = 0;
                 j < column; j++) {
 
                ThreeDLinkedListNode*
                    start
                    = node;
 
                // Loop to traverse
                // each row
                for (int k = 0;
                     k < row; k++) {
 
                    // Check if its the
                    // last cell of the
                    // current row
                    if (k == row - 1)
                        node->down = start;
                    else
                        node->down
                            = new ThreeDLinkedListNode(
                                a[i][k + 1][j]);
 
                    node = node->down;
                }
 
                // Check if it is the last
                // element of the current
                // column
                if (j == column - 1) {
 
                    node->right = start_layer_head;
 
                    // Check if it is the
                    // last element of the
                    // current layer
                    if (i < layer - 1) {
 
                        start_layer_head->back
                            = new ThreeDLinkedListNode(
                                a[i + 1][0][0]);
 
                        node = start_layer_head->back;
                    }
                    else {
 
                        start_layer_head->back = head;
                        node = start_layer_head->back;
                    }
                }
                else {
 
                    node->right
                        = new ThreeDLinkedListNode(
                            a[i][0][j + 1]);
                    node = node->right;
                }
            }
        }
    }
 
    void setUp(
        vector<vector<vector<int> > > a,
        int layer, int row, int column,
        ThreeDLinkedListNode* node)
    {
 
        // setting the up pointers of all
        // nodes in a 3d linked list
        ThreeDLinkedListNode* head = node;
 
        // loop to traverse the layers
        for (int i = 0;
             i < layer; i++) {
 
            ThreeDLinkedListNode*
                start_layer_head
                = node;
 
            // Loop to traverse the
            // columns
            for (int j = 0;
                 j < column; j++) {
 
                ThreeDLinkedListNode*
                    start
                    = node;
 
                // Loop to traverse
                // the rows
                for (int k = 0;
                     k < row; k++) {
 
                    node->down->up = node;
                    node = node->down;
                }
 
                // Check if it is the
                // last element of
                // the column
                if (j == column - 1) {
 
                    node
                        = start_layer_head->back;
                }
                else {
                    node = node->right;
                }
            }
        }
    }
 
    void setRight(
        vector<vector<vector<int> > > a,
        int layer, int row, int column,
        ThreeDLinkedListNode* node)
    {
        // setting the Right pointers of
        // all nodes in a 3d linked list
        ThreeDLinkedListNode* head = node;
 
        // loop to traverse the layers
        for (int i = 0;
             i < layer; i++) {
 
            ThreeDLinkedListNode*
                start_layer_head
                = node;
 
            // loop to traverse the
            // columns
            for (int j = 0;
                 j < column; j++) {
 
                ThreeDLinkedListNode*
                    start
                    = node;
 
                // loop to traverse
                // the rows
                for (int k = 0;
                     k < row; k++) {
 
                    node->down->right
                        = node->right->down;
                    node = node->down;
                }
 
                // Check if it is the
                // last element of the
                // column
                if (j == column - 1) {
                    node
                        = start_layer_head->back;
                }
                else {
                    node = node->right;
                }
            }
        }
    }
 
    void setLeft(
        vector<vector<vector<int> > > a,
        int layer, int row, int column,
        ThreeDLinkedListNode* node)
    {
 
        // setting the Left pointers of
        // all nodes in a 3d linked list
        ThreeDLinkedListNode* head = node;
 
        // loop to traverse the layers
        for (int i = 0;
             i < layer; i++) {
 
            ThreeDLinkedListNode*
                start_layer_head
                = node;
 
            // loop to traverse the
            // columns
            for (int j = 0;
                 j < column; j++) {
 
                ThreeDLinkedListNode*
                    start
                    = node;
 
                // loop to traverse
                // the rows`
                for (int k = 0;
                     k < row; k++) {
 
                    node->right->left = node;
                    node = node->down;
                }
 
                // Check if it is the
                // last element of the
                // column
                if (j == column - 1) {
                    node
                        = start_layer_head->back;
                }
                else {
                    node = node->right;
                }
            }
        }
    }
 
    void setBack(
        vector<vector<vector<int> > > a,
        int layer, int row, int column,
        ThreeDLinkedListNode* node)
    {
 
        // setting the Back pointers of
        // all nodes in a 3d linked list
        ThreeDLinkedListNode* head = node;
 
        // loop to traverse the layers
        for (int i = 0;
             i < layer; i++) {
 
            ThreeDLinkedListNode*
                start_layer_head
                = node;
 
            // loop to traverse the
            // columns
            for (int j = 0;
                 j < column; j++) {
 
                ThreeDLinkedListNode*
                    start
                    = node;
 
                // loop to traverse
                // the rows
                for (int k = 0;
                     k < row; k++) {
 
                    node->down->back
                        = node->back->down;
                    node = node->down;
                }
 
                // Check if it is the
                // last element of the
                // column
                if (j == column - 1) {
                    node = start_layer_head->back;
                }
                else {
                    node = node->right;
                    node->back = start->back->right;
                }
            }
        }
    }
 
    void setFront(
        vector<vector<vector<int> > > a,
        int layer, int row, int column,
        ThreeDLinkedListNode* node)
    {
 
        // setting the Front pointers of
        // all nodes in a 3d linked list
        ThreeDLinkedListNode* head = node;
 
        // loop to traverse the layers
        for (int i = 0;
             i < layer; i++) {
 
            ThreeDLinkedListNode*
                start_layer_head
                = node;
 
            // loop to traverse the
            // columns
            for (int j = 0;
                 j < column; j++) {
 
                ThreeDLinkedListNode*
                    start
                    = node;
 
                // loop to traverse
                // the rows
                for (int k = 0;
                     k < row; k++) {
 
                    node->back->front = node;
                    node = node->down;
                }
 
                // Check if it is the
                // last element of the
                // column
                if (j == column - 1) {
                    node = start_layer_head->back;
                }
                else {
                    node = node->right;
                    node->back = start->back->right;
                }
            }
        }
    }
 
    ThreeDLinkedListNode*
    ThreeDimensionalMatrixToLinkedList(
        vector<vector<vector<int> > > a,
        int layer, int row, int column)
    {
        ThreeDLinkedListNode* head
            = new ThreeDLinkedListNode(
                a[0][0][0]);
 
        ThreeDLinkedListNode* temp = head;
 
        // setting down pointers
        // of all the nodes
        setDown(a, layer,
                row, column, temp);
 
        // setting up pointers
        // of all the nodes
        setUp(a, layer,
              row, column, temp);
 
        // setting right pointers
        // of all the nodes
        setRight(a, layer,
                 row, column, temp);
 
        // setting left pointers
        // of all the nodes
        setLeft(a, layer,
                row, column, temp);
 
        // setting back pointers
        // of all the nodes
        setBack(a, layer,
                row, column, temp);
 
        // setting front pointers
        // of all the nodes
        setFront(a, layer,
                 row, column, temp);
 
        return head;
    }
};
 
void print_2d_matrix(
    vector<vector<vector<int> > > mat,
    ThreeDLinkedListNode* head,
    int rows, int cols, int layer)
{
 
    ThreeDLinkedListNode* rest;
 
    // loop to traverse
    // the rows
    for (int i = 0;
         i < rows; ++i) {
 
        rest = head->down;
 
        // loop to traverse
        // the columns
        for (int j = 0;
             j < cols; ++j) {
 
            cout << mat[layer][i][j]
                 << "\t";
            vector<int> neighbors
                = head->extractNeighbors();
            for (auto ne : neighbors)
                cout << ne << "\t";
 
            cout << "\n";
            head = head->right;
        }
        head = rest;
    }
}
 
void printOutput(
    vector<vector<vector<int> > > mat,
    ThreeDLinkedListNode* head,
    int layer, int row, int column)
{
 
    ThreeDLinkedListNode* rest;
 
    // loop to traverse the layers
    for (int i = 0;
         i < layer; i++) {
 
        rest = head->back;
        print_2d_matrix(mat, head,
                        row, column, i);
        head = rest;
    }
}
 
// Driver Code
int main()
{
    // Initialise the count
    // of layers, columns and
    // rows
    int layer = 3;
    int row = 3;
    int column = 3;
 
    vector<vector<vector<int> > >
    mat(layer,
        vector<vector<int> >(
            row, vector<int>(column)));
 
    mat = { { { 1, 2, 3 },
              { 4, 5, 6 },
              { 7, 8, 9 } },
            { { 10, 11, 12 },
              { 13, 14, 15 },
              { 16, 17, 18 } },
            { { 19, 20, 21 },
              { 22, 23, 24 },
              { 25, 26, 27 } } };
 
    // Function Call to form
    // the linked list for the
    // given 3D matrix
    ThreeDLinkedListNode*
        head
        = Solution()
              .ThreeDimensionalMatrixToLinkedList(
                  mat, layer, row, column);
 
    cout << "element\t"
         << "front\tback\t"
         << "left\tright\t"
         << "up\tdown\n";
 
    // Function to print the
    // linked list elements
    // and thevalues pointed
    // by corresponding pointers
    printOutput(mat, head,
                layer, row, column);
    return 0;
}


Java




import java.util.*;
 
// Node structure of the 3D-linked list
class ThreeDLinkedListNode {
    int val;
    ThreeDLinkedListNode front, back, up, right, down, left;
 
    // Constructor
    ThreeDLinkedListNode(int x) {
        this.val = x;
    }
 
    // Method to extract all neighbors of the node
    List<Integer> extractNeighbors() {
        List<Integer> neighbour = new ArrayList<>();
        neighbour.add(front.val);
        neighbour.add(back.val);
        neighbour.add(left.val);
        neighbour.add(right.val);
        neighbour.add(up.val);
        neighbour.add(down.val);
        return neighbour;
    }
}
 
public class Main {
    // Method to set down pointers of all nodes in a 3D linked list
    static void setDown(int[][][] a, int layer, int row, int column, ThreeDLinkedListNode node) {
        ThreeDLinkedListNode head = node;
        for (int i = 0; i < layer; i++) {
            ThreeDLinkedListNode start_layer_head = node;
            for (int j = 0; j < column; j++) {
                ThreeDLinkedListNode start = node;
                for (int k = 0; k < row; k++) {
                    if (k == row - 1)
                        node.down = start;
                    else
                        node.down = new ThreeDLinkedListNode(a[i][k + 1][j]);
                    node = node.down;
                }
                if (j == column - 1) {
                    node.right = start_layer_head;
                    if (i < layer - 1) {
                        start_layer_head.back = new ThreeDLinkedListNode(a[i + 1][0][0]);
                        node = start_layer_head.back;
                    } else {
                        start_layer_head.back = head;
                        node = start_layer_head.back;
                    }
                } else {
                    node.right = new ThreeDLinkedListNode(a[i][0][j + 1]);
                    node = node.right;
                }
            }
        }
    }
 
    // Method to set up pointers of all nodes in a 3D linked list
    static void setUp(int[][][] a, int layer, int row, int column, ThreeDLinkedListNode node) {
        ThreeDLinkedListNode head = node;
        for (int i = 0; i < layer; i++) {
            ThreeDLinkedListNode start_layer_head = node;
            for (int j = 0; j < column; j++) {
                ThreeDLinkedListNode start = node;
                for (int k = 0; k < row; k++) {
                    node.down.up = node;
                    node = node.down;
                }
                if (j == column - 1) {
                    node = start_layer_head.back;
                } else {
                    node = node.right;
                }
            }
        }
    }
 
    // Method to set right pointers of all nodes in a 3D linked list
    static void setRight(int[][][] a, int layer, int row, int column, ThreeDLinkedListNode node) {
        ThreeDLinkedListNode head = node;
        for (int i = 0; i < layer; i++) {
            ThreeDLinkedListNode start_layer_head = node;
            for (int j = 0; j < column; j++) {
                ThreeDLinkedListNode start = node;
                for (int k = 0; k < row; k++) {
                    node.down.right = node.right.down;
                    node = node.down;
                }
                if (j == column - 1) {
                    node = start_layer_head.back;
                } else {
                    node = node.right;
                }
            }
        }
    }
 
    // Method to set left pointers of all nodes in a 3D linked list
    static void setLeft(int[][][] a, int layer, int row, int column, ThreeDLinkedListNode node) {
        ThreeDLinkedListNode head = node;
        for (int i = 0; i < layer; i++) {
            ThreeDLinkedListNode start_layer_head = node;
            for (int j = 0; j < column; j++) {
                ThreeDLinkedListNode start = node;
                for (int k = 0; k < row; k++) {
                    node.right.left = node;
                    node = node.down;
                }
                if (j == column - 1) {
                    node = start_layer_head.back;
                } else {
                    node = node.right;
                }
            }
        }
    }
 
    // Method to set back pointers of all nodes in a 3D linked list
    static void setBack(int[][][] a, int layer, int row, int column, ThreeDLinkedListNode node) {
        ThreeDLinkedListNode head = node;
        for (int i = 0; i < layer; i++) {
            ThreeDLinkedListNode start_layer_head = node;
            for (int j = 0; j < column; j++) {
                ThreeDLinkedListNode start = node;
                for (int k = 0; k < row; k++) {
                    node.down.back = node.back.down;
                    node = node.down;
                }
                if (j == column - 1) {
                    node = start_layer_head.back;
                } else {
                    node = node.right;
                    node.back = start.back.right;
                }
            }
        }
    }
 
    // Method to set front pointers of all nodes in a 3D linked list
    static void setFront(int[][][] a, int layer, int row, int column, ThreeDLinkedListNode node) {
        ThreeDLinkedListNode head = node;
        for (int i = 0; i < layer; i++) {
            ThreeDLinkedListNode start_layer_head = node;
            for (int j = 0; j < column; j++) {
                ThreeDLinkedListNode start = node;
                for (int k = 0; k < row; k++) {
                    node.back.front = node;
                    node = node.down;
                }
                if (j == column - 1) {
                    node = start_layer_head.back;
                } else {
                    node = node.right;
                    node.back = start.back.right;
                }
            }
        }
    }
 
    // Method to convert a 3D matrix into a 3D linked list
    static ThreeDLinkedListNode threeDimensionalMatrixToLinkedList(int[][][] a, int layer, int row, int column) {
        ThreeDLinkedListNode head = new ThreeDLinkedListNode(a[0][0][0]);
        setDown(a, layer, row, column, head);
        setUp(a, layer, row, column, head);
        setRight(a, layer, row, column, head);
        setLeft(a, layer, row, column, head);
        setBack(a, layer, row, column, head);
        setFront(a, layer, row, column, head);
        return head;
    }
 
    // Method to print the 3D linked list
    static void printOutput(int[][][] mat, ThreeDLinkedListNode head, int layer, int row, int column) {
        ThreeDLinkedListNode rest;
        for (int i = 0; i < layer; i++) {
            rest = head.back;
            for (int j = 0; j < row; j++) {
                ThreeDLinkedListNode temp = head.down;
                for (int k = 0; k < column; k++) {
                    System.out.print(mat[i][j][k] + "\t");
                    List<Integer> neighbors = head.extractNeighbors();
                    for (int ne : neighbors)
                        System.out.print(ne + "\t");
                    System.out.println();
                    head = head.right;
                }
                head = temp;
            }
            head = rest;
        }
    }
 
    // Main method
    public static void main(String[] args) {
        int layer = 3, row = 3, column = 3;
        int[][][] mat = {
            { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } },
            { { 10, 11, 12 }, { 13, 14, 15 }, { 16, 17, 18 } },
            { { 19, 20, 21 }, { 22, 23, 24 }, { 25, 26, 27 } }
        };
        ThreeDLinkedListNode head = threeDimensionalMatrixToLinkedList(mat, layer, row, column);
        System.out.println("element\tfront\tback\tleft\tright\tup\tdown");
        printOutput(mat, head, layer, row, column);
    }
}


Javascript




class ThreeDLinkedListNode {
    constructor(x) {
        this.val = x;
        this.front = null;
        this.back = null;
        this.up = null;
        this.right = null;
        this.down = null;
        this.left = null;
    }
 
    // Method to extract all neighbors of the node
    extractNeighbors() {
        return [this.front.val, this.back.val, this.left.val, this.right.val, this.up.val, this.down.val];
    }
}
 
// Function to set down pointers of all nodes in a 3D linked list
function setDown(a, layer, row, column, node) {
    let head = node;
    for (let i = 0; i < layer; i++) {
        let start_layer_head = node;
        for (let j = 0; j < column; j++) {
            let start = node;
            for (let k = 0; k < row; k++) {
                if (k === row - 1)
                    node.down = start;
                else
                    node.down = new ThreeDLinkedListNode(a[i][k + 1][j]);
                node = node.down;
            }
            if (j === column - 1) {
                node.right = start_layer_head;
                if (i < layer - 1) {
                    start_layer_head.back = new ThreeDLinkedListNode(a[i + 1][0][0]);
                    node = start_layer_head.back;
                } else {
                    start_layer_head.back = head;
                    node = start_layer_head.back;
                }
            } else {
                node.right = new ThreeDLinkedListNode(a[i][0][j + 1]);
                node = node.right;
            }
        }
    }
}
 
// Function to set up pointers of all nodes in a 3D linked list
function setUp(a, layer, row, column, node) {
    let head = node;
    for (let i = 0; i < layer; i++) {
        let start_layer_head = node;
        for (let j = 0; j < column; j++) {
            let start = node;
            for (let k = 0; k < row; k++) {
                node.down.up = node;
                node = node.down;
            }
            if (j === column - 1) {
                node = start_layer_head.back;
            } else {
                node = node.right;
            }
        }
    }
}
 
// Function to set right pointers of all nodes in a 3D linked list
function setRight(a, layer, row, column, node) {
    let head = node;
    for (let i = 0; i < layer; i++) {
        let start_layer_head = node;
        for (let j = 0; j < column; j++) {
            let start = node;
            for (let k = 0; k < row; k++) {
                node.down.right = node.right.down;
                node = node.down;
            }
            if (j === column - 1) {
                node = start_layer_head.back;
            } else {
                node = node.right;
            }
        }
    }
}
 
// Function to set left pointers of all nodes in a 3D linked list
function setLeft(a, layer, row, column, node) {
    let head = node;
    for (let i = 0; i < layer; i++) {
        let start_layer_head = node;
        for (let j = 0; j < column; j++) {
            let start = node;
            for (let k = 0; k < row; k++) {
                node.right.left = node;
                node = node.down;
            }
            if (j === column - 1) {
                node = start_layer_head.back;
            } else {
                node = node.right;
            }
        }
    }
}
 
// Function to set back pointers of all nodes in a 3D linked list
function setBack(a, layer, row, column, node) {
    let head = node;
    for (let i = 0; i < layer; i++) {
        let start_layer_head = node;
        for (let j = 0; j < column; j++) {
            let start = node;
            for (let k = 0; k < row; k++) {
                node.down.back = node.back.down;
                node = node.down;
            }
            if (j === column - 1) {
                node = start_layer_head.back;
            } else {
                node = node.right;
                node.back = start.back.right;
            }
        }
    }
}
 
// Function to set front pointers of all nodes in a 3D linked list
function setFront(a, layer, row, column, node) {
    let head = node;
    for (let i = 0; i < layer; i++) {
        let start_layer_head = node;
        for (let j = 0; j < column; j++) {
            let start = node;
            for (let k = 0; k < row; k++) {
                node.back.front = node;
                node = node.down;
            }
            if (j === column - 1) {
                node = start_layer_head.back;
            } else {
                node = node.right;
                node.back = start.back.right;
            }
        }
    }
}
 
// Function to convert a 3D matrix into a 3D linked list
function threeDimensionalMatrixToLinkedList(a, layer, row, column) {
    let head = new ThreeDLinkedListNode(a[0][0][0]);
    setDown(a, layer, row, column, head);
    setUp(a, layer, row, column, head);
    setRight(a, layer, row, column, head);
    setLeft(a, layer, row, column, head);
    setBack(a, layer, row, column, head);
    setFront(a, layer, row, column, head);
    return head;
}
 
// Function to print the 3D linked list
function printOutput(mat, head, layer, row, column) {
    let rest;
    for (let i = 0; i < layer; i++) {
        rest = head.back;
        for (let j = 0; j < row; j++) {
            let temp = head.down;
            for (let k = 0; k < column; k++) {
                console.log(mat[i][j][k] + "\t");
                let neighbors = head.extractNeighbors();
                for (let ne of neighbors)
                    console.log(ne + "\t");
                console.log();
                head = head.right;
            }
            head = temp;
        }
        head = rest;
    }
}
 
// Main function
function main() {
    let layer = 3, row = 3, column = 3;
    let mat = [
        [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ],
        [ [ 10, 11, 12 ], [ 13, 14, 15 ], [ 16, 17, 18 ] ],
        [ [ 19, 20, 21 ], [ 22, 23, 24 ], [ 25, 26, 27 ] ]
    ];
    let head = threeDimensionalMatrixToLinkedList(mat, layer, row, column);
    console.log("element\tfront\tback\tleft\tright\tup\tdown");
    printOutput(mat, head, layer, row, column);
}
 
main();


Python3




class ThreeDLinkedListNode:
    def __init__(self, x, f=None, b=None, u=None, r=None, d=None, l=None):
        # Initialize the node with value and six neighbors
        self.val = x
        self.front = f
        self.back = b
        self.up = u
        self.right = r
        self.down = d
        self.left = l
 
    def extract_neighbors(self):
        # Extract the values of the neighbors
        return [self.front.val, self.back.val, self.left.val, self.right.val, self.up.val, self.down.val]
 
 
class Solution:
    # The following methods set the neighbors for each node in the 3D linked list
    def set_down(self, a, layer, row, column, node):
        # Set the down neighbor for each node
        head = node
        for i in range(layer):
            start_layer_head = node
            for j in range(column):
                start = node
                for k in range(row):
                    if k == row - 1:
                        node.down = start
                    else:
                        node.down = ThreeDLinkedListNode(a[i][k + 1][j])
                    node = node.down
                if j == column - 1:
                    node.right = start_layer_head
                    if i < layer - 1:
                        start_layer_head.back = ThreeDLinkedListNode(a[i + 1][0][0])
                        node = start_layer_head.back
                    else:
                        start_layer_head.back = head
                        node = start_layer_head.back
                else:
                    node.right = ThreeDLinkedListNode(a[i][0][j + 1])
                    node = node.right
 
    def set_up(self, a, layer, row, column, node):
        # Set the up neighbor for each node
        head = node
        for i in range(layer):
            start_layer_head = node
            for j in range(column):
                start = node
                for k in range(row):
                    node.down.up = node
                    node = node.down
                if j == column - 1:
                    node = start_layer_head.back
                else:
                    node = node.right
 
    def set_right(self, a, layer, row, column, node):
        # Set the right neighbor for each node
        head = node
        for i in range(layer):
            start_layer_head = node
            for j in range(column):
                start = node
                for k in range(row):
                    node.down.right = node.right.down
                    node = node.down
                if j == column - 1:
                    node = start_layer_head.back
                else:
                    node = node.right
 
    def set_left(self, a, layer, row, column, node):
        # Set the left neighbor for each node
        head = node
        for i in range(layer):
            start_layer_head = node
            for j in range(column):
                start = node
                for k in range(row):
                    node.right.left = node
                    node = node.down
                if j == column - 1:
                    node = start_layer_head.back
                else:
                    node = node.right
 
    def set_back(self, a, layer, row, column, node):
        # Set the back neighbor for each node
        head = node
        for i in range(layer):
            start_layer_head = node
            for j in range(column):
                start = node
                for k in range(row):
                    node.down.back = node.back.down
                    node = node.down
                if j == column - 1:
                    node = start_layer_head.back
                else:
                    node = node.right
                    node.back = start.back.right
 
    def set_front(self, a, layer, row, column, node):
        # Set the front neighbor for each node
        head = node
        for i in range(layer):
            start_layer_head = node
            for j in range(column):
                start = node
                for k in range(row):
                    node.back.front = node
                    node = node.down
                if j == column - 1:
                    node = start_layer_head.back
                else:
                    node = node.right
                    node.back = start.back.right
 
    def three_dimensional_matrix_to_linked_list(self, a, layer, row, column):
        # Convert a 3D matrix to a 3D linked list
        head = ThreeDLinkedListNode(a[0][0][0])
        temp = head
        self.set_down(a, layer, row, column, temp)
        self.set_up(a, layer, row, column, temp)
        self.set_right(a, layer, row, column, temp)
        self.set_left(a, layer, row, column, temp)
        self.set_back(a, layer, row, column, temp)
        self.set_front(a, layer, row, column, temp)
        return head
 
 
def print_2d_matrix(mat, head, rows, cols, layer):
    # Print a 2D matrix and the neighbors of each node
    rest = head.down
    for i in range(rows):
        for j in range(cols):
            print(mat[layer][i][j], end="\t")
            neighbors = head.extract_neighbors()
            for ne in neighbors:
                print(ne, end="\t")
            print()
            head = head.right
        head = rest
 
 
def print_output(mat, head, layer, row, column):
    # Print the output for each layer of the 3D matrix
    rest = head.back
    for i in range(layer):
        print_2d_matrix(mat, head, row, column, i)
        head = rest
 
 
def main():
    # Main function to test the 3D linked list
    layer = 3
    row = 3
    column = 3
    mat = [[[1, 2, 3], [4, 5, 6], [7, 8, 9]],
           [[10, 11, 12], [13, 14, 15], [16, 17, 18]],
           [[19, 20, 21], [22, 23, 24], [25, 26, 27]]]
    head = Solution().three_dimensional_matrix_to_linked_list(mat, layer, row, column)
    print("element\tfront\tback\tleft\tright\tup\tdown")
    print_output(mat, head, layer, row, column)
 
 
if __name__ == "__main__":
    main()


Output

element    front    back    left    right    up    down
1    19    10    3    2    7    4    
2    20    11    1    3    8    5    
3    21    12    2    1    9    6    
4    22    13    6    5    1    7    
5    23    14    4    6    2    8    
6    24    15    5    4    3    9    
7    25    16    9    8    4    1    
8    26    17    7    9    5    2    
9    27    18    8    7    6    3    
10    1    19    12    11    16    13    
11    2    20    10    12    17    14    
12    3    21    11    10    18    15    
13    4    22    15    14    10    16    
14    5    23    13    15    11    17    
15    6    24    14    13    12    18    
16    7    25    18    17    13    10    
17    8    26    16    18    14    11    
18    9    27    17    16    15    12    
19    10    1    21    20    25    22    
20    11    2    19    21    26    23    
21    12    3    20    19    27    24    
22    13    4    24    23    19    25    
23    14    5    22    24    20    26    
24    15    6    23    22    21    27    
25    16    7    27    26    22    19    
26    17    8    25    27    23    20    
27    18    9    26    25    24    21




Time Complexity: O(X * Y * Z), where X, Y, Z are the dimensions of the 3D matrix. 
Auxiliary Space: O(X * Y * Z), where X, Y, Z are the dimensions of the 3D matrix.
 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads