In: Computer Science
I have written the program using JAVA PROGRAMMING LANGUAGE.
OUTPUT :
CODE :
public class Main {
// Structure for Node
static class Node {
int data;
Node right;
Node down;
};
// To construct the linked list for the given 2D array
static Node construct(int arr[][], int i, int j,
int m, int n) {
// return if i or j is out of bounds
if (i > n - 1 || j > m - 1)
return null;
Node temp = new Node();
temp.data = arr[i][j];
temp.right = construct(arr, i, j + 1, m, n);
temp.down = construct(arr, i + 1, j, m, n);
return temp;
}
//To display the linked list
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;
}
}
static void Transpose_display(Node head){
// pointer to move down
Node Dp;
// pointer to move right
Node Rp = head;
// loop till node->right is not NULL
while (Rp != null) {
Dp = Rp;
// loop till node->down is not NULL
while (Dp != null) {
System.out.print(Dp.data + " ");
Dp = Dp.down;
}
System.out.println();
Rp = Rp.right;
}
}
// main method
public static void main(String args[]) {
// Two dimentiional matrix
int arr[][] = { { 1, 2, 3 },
{ 4, 5, 6 },
{ 7, 8, 9 } };
int m = 3, n = 3; // to define the row and column
Node head = construct(arr, 0, 0, m, n); //To construc the Linked list
System.out.println("Input Matrix : \n");
display(head); //Calling display method
System.out.println();
System.out.println("Transpose Matrix : \n");
Transpose_display(head);//Calling Transpose_display method
}
}
Thanks..