Sparse Matrix and its representations | Set 2 (Using List of Lists and Dictionary of keys)
Prerequisite : Sparse Matrix and its representations Set 1 (Using Arrays and Linked Lists)
In this post other two methods of sparse matrix representation are discussed.
- List of Lists
- Dictionary
List of Lists (LIL)
One of the possible representation of sparse matrix is List of Lists (LIL). Where one list is used to represent the rows and each row contains the list of triples: Column index, Value(non – zero element) and address field, for non – zero elements. For the best performance both lists should be stored in order of ascending keys.
Implementation:
C++
// C++ program for Sparse Matrix Representation // using List Of Lists #include<bits/stdc++.h> using namespace std; #define R 4 #define C 5 // Node to represent row - list struct row_list { int row_number; struct row_list *link_down; struct value_list *link_right; }; // Node to represent triples struct value_list { int column_index; int value; struct value_list *next; }; // Function to create node for non - zero elements void create_value_node( int data, int j, struct row_list **z) { struct value_list *temp, *d; // Create new node dynamically temp = new value_list(); temp->column_index = j+1; temp->value = data; temp->next = NULL; // Connect with row list if ((*z)->link_right==NULL) (*z)->link_right = temp; else { // d points to data list node d = (*z)->link_right; while (d->next != NULL) d = d->next; d->next = temp; } } // Function to create row list void create_row_list( struct row_list **start, int row, int column, int Sparse_Matrix[R][C]) { // For every row, node is created for ( int i = 0; i < row; i++) { struct row_list *z, *r; // Create new node dynamically z = new row_list(); z->row_number = i+1; z->link_down = NULL; z->link_right = NULL; if (i==0) *start = z; else { r = *start; while (r->link_down != NULL) r = r->link_down; r->link_down = z; } // Firstly node for row is created, // and then traversing is done in that row for ( int j = 0; j < 5; j++) { if (Sparse_Matrix[i][j] != 0) { create_value_node(Sparse_Matrix[i][j], j, &z); } } } } //Function display data of LIL void print_LIL( struct row_list *start) { struct row_list *r; struct value_list *z; r = start; // Traversing row list while (r != NULL) { if (r->link_right != NULL) { cout<< "row=" <<r->row_number<<endl; z = r->link_right; // Traversing data list while (z != NULL) { cout<< "column=" <<z->column_index<< " value=" <<z->value<<endl; z = z->next; } } r = r->link_down; } } //Driver of the program int main() { // Assume 4x5 sparse matrix int Sparse_Matrix[R][C] = { {0 , 0 , 3 , 0 , 4 }, {0 , 0 , 5 , 7 , 0 }, {0 , 0 , 0 , 0 , 0 }, {0 , 2 , 6 , 0 , 0 } }; // Start with the empty List of lists struct row_list* start = NULL; //Function creating List of Lists create_row_list(&start, R, C, Sparse_Matrix); // Display data of List of lists print_LIL(start); return 0; } // This code is contributed by rutvik_56. |
C
// C program for Sparse Matrix Representation // using List Of Lists #include<stdio.h> #include<stdlib.h> #define R 4 #define C 5 // Node to represent row - list struct row_list { int row_number; struct row_list *link_down; struct value_list *link_right; }; // Node to represent triples struct value_list { int column_index; int value; struct value_list *next; }; // Function to create node for non - zero elements void create_value_node( int data, int j, struct row_list **z) { struct value_list *temp, *d; // Create new node dynamically temp = ( struct value_list*) malloc ( sizeof ( struct value_list)); temp->column_index = j+1; temp->value = data; temp->next = NULL; // Connect with row list if ((*z)->link_right==NULL) (*z)->link_right = temp; else { // d points to data list node d = (*z)->link_right; while (d->next != NULL) d = d->next; d->next = temp; } } // Function to create row list void create_row_list( struct row_list **start, int row, int column, int Sparse_Matrix[R][C]) { // For every row, node is created for ( int i = 0; i < row; i++) { struct row_list *z, *r; // Create new node dynamically z = ( struct row_list*) malloc ( sizeof ( struct row_list)); z->row_number = i+1; z->link_down = NULL; z->link_right = NULL; if (i==0) *start = z; else { r = *start; while (r->link_down != NULL) r = r->link_down; r->link_down = z; } // Firstly node for row is created, // and then traversing is done in that row for ( int j = 0; j < 5; j++) { if (Sparse_Matrix[i][j] != 0) { create_value_node(Sparse_Matrix[i][j], j, &z); } } } } //Function display data of LIL void print_LIL( struct row_list *start) { struct row_list *r; struct value_list *z; r = start; // Traversing row list while (r != NULL) { if (r->link_right != NULL) { printf ( "row=%d \n" , r->row_number); z = r->link_right; // Traversing data list while (z != NULL) { printf ( "column=%d value=%d \n" , z->column_index, z->value); z = z->next; } } r = r->link_down; } } //Driver of the program int main() { // Assume 4x5 sparse matrix int Sparse_Matrix[R][C] = { {0 , 0 , 3 , 0 , 4 }, {0 , 0 , 5 , 7 , 0 }, {0 , 0 , 0 , 0 , 0 }, {0 , 2 , 6 , 0 , 0 } }; // Start with the empty List of lists struct row_list* start = NULL; //Function creating List of Lists create_row_list(&start, R, C, Sparse_Matrix); // Display data of List of lists print_LIL(start); return 0; } |
Java
// Java program for Sparse Matrix Representation // using List Of Lists class GFG { static int R = 4 ; static int C = 5 ; // Node to represent row - list static class row_list { int row_number; row_list link_down; value_list link_right; }; // Node to represent triples static class value_list { int column_index; int value; value_list next; }; // Function to create node for non - zero elements static row_list create_value_node( int data, int j, row_list z) { value_list temp, d; // Create new node dynamically temp = new value_list(); temp.column_index = j+ 1 ; temp.value = data; temp.next = null ; // Connect with row list if (z.link_right== null ) z.link_right = temp; else { // d points to data list node d = z.link_right; while (d.next != null ) d = d.next; d.next = temp; } return z; } // Function to create row list static row_list create_row_list(row_list start, int row, int column, int Sparse_Matrix[][]) { // For every row, node is created for ( int i = 0 ; i < row; i++) { row_list z, r; // Create new node dynamically z = new row_list(); z.row_number = i+ 1 ; z.link_down = null ; z.link_right = null ; if (i== 0 ) start = z; else { r = start; while (r.link_down != null ) r = r.link_down; r.link_down = z; } // Firstly node for row is created, // and then traversing is done in that row for ( int j = 0 ; j < 5 ; j++) { if (Sparse_Matrix[i][j] != 0 ) { z = create_value_node(Sparse_Matrix[i][j], j, z); } } } return start; } //Function display data of LIL static void print_LIL(row_list start) { row_list r; value_list z; r = start; // Traversing row list while (r != null ) { if (r.link_right != null ) { System.out.println( "row=" + r.row_number); z = r.link_right; // Traversing data list while (z != null ) { System.out.println( "column=" +z.column_index+ " value=" +z.value); z = z.next; } } r = r.link_down; } } //Driver of the program public static void main(String[] args) { // Assume 4x5 sparse matrix int Sparse_Matrix[][] = { { 0 , 0 , 3 , 0 , 4 }, { 0 , 0 , 5 , 7 , 0 }, { 0 , 0 , 0 , 0 , 0 }, { 0 , 2 , 6 , 0 , 0 } }; // Start with the empty List of lists row_list start = null ; //Function creating List of Lists start = create_row_list(start, R, C, Sparse_Matrix); // Display data of List of lists print_LIL(start); } } // This code is contributed by phasing17. |
Python3
# Python3 program for Sparse Matrix Representation # using List Of Lists R = 4 ; C = 5 ; # Node to represent row - list class row_list : def __init__( self ): self .row_number = None ; self .link_down = None ; self .link_right = None ; # Node to represent triples class value_list : def __init__( self ): self .column_index = None ; self .value = None ; self . next = None ; # Function to create node for non - zero elements def create_value_node(data, j, z): # Create node dynamically temp = value_list(); temp.column_index = j + 1 ; temp.value = data; temp. next = None ; # Connect with row list if (z.link_right = = None ): z.link_right = temp; else : # d points to data list node d = z.link_right; while (d. next ! = None ): d = d. next ; d. next = temp; return z; # Function to create row list def create_row_list(start, row, column, Sparse_Matrix): # For every row, node is created for i in range (row): # Create node dynamically z = row_list(); z.row_number = i + 1 ; z.link_down = None ; z.link_right = None ; if (i = = 0 ): start = z; else : r = start; while (r.link_down ! = None ): r = r.link_down; r.link_down = z; # Firstly node for row is created, # and then traversing is done in that row for j in range ( 5 ): if (Sparse_Matrix[i][j] ! = 0 ) : z = create_value_node(Sparse_Matrix[i][j],j, z); return start; # Function display data of LIL def print_LIL(start): r = start; # Traversing row list while (r ! = None ) : if (r.link_right ! = None ) : print ( "row=" , r.row_number); z = r.link_right; # Traversing data list while (z ! = None ) : print ( "column=" , z.column_index, " value=" , z.value); z = z. next ; r = r.link_down; # Driver of the program # Assume 4x5 sparse matrix Sparse_Matrix = [[ 0 , 0 , 3 , 0 , 4 ], [ 0 , 0 , 5 , 7 , 0 ], [ 0 , 0 , 0 , 0 , 0 ], [ 0 , 2 , 6 , 0 , 0 ]]; # Start with the empty List of lists start = None ; # Function creating List of Lists start = create_row_list(start, R, C, Sparse_Matrix); # Display data of List of lists print_LIL(start); # This code is contributed by phasing17. |
C#
// C# program for Sparse Matrix Representation // using List Of Lists using System; // Node to represent row - list class row_list { public int row_number; public row_list link_down; public value_list link_right; }; // Node to represent triples class value_list { public int column_index; public int value; public value_list next; }; class GFG { static int R = 4; static int C = 5; // Function to create node for non - zero elements static row_list create_value_node( int data, int j, row_list z) { value_list temp, d; // Create new node dynamically temp = new value_list(); temp.column_index = j + 1; temp.value = data; temp.next = null ; // Connect with row list if (z.link_right == null ) z.link_right = temp; else { // d points to data list node d = z.link_right; while (d.next != null ) d = d.next; d.next = temp; } return z; } // Function to create row list static row_list create_row_list(row_list start, int row, int column, int [, ] Sparse_Matrix) { // For every row, node is created for ( int i = 0; i < row; i++) { row_list z, r; // Create new node dynamically z = new row_list(); z.row_number = i + 1; z.link_down = null ; z.link_right = null ; if (i == 0) start = z; else { r = start; while (r.link_down != null ) r = r.link_down; r.link_down = z; } // Firstly node for row is created, // and then traversing is done in that row for ( int j = 0; j < 5; j++) { if (Sparse_Matrix[i, j] != 0) { z = create_value_node( Sparse_Matrix[i, j], j, z); } } } return start; } // Function display data of LIL static void print_LIL(row_list start) { row_list r; value_list z; r = start; // Traversing row list while (r != null ) { if (r.link_right != null ) { Console.WriteLine( "row=" + r.row_number); z = r.link_right; // Traversing data list while (z != null ) { Console.WriteLine( "column=" + z.column_index + " value=" + z.value); z = z.next; } } r = r.link_down; } } // Driver of the program public static void Main( string [] args) { // Assume 4x5 sparse matrix int [, ] Sparse_Matrix = { { 0, 0, 3, 0, 4 }, { 0, 0, 5, 7, 0 }, { 0, 0, 0, 0, 0 }, { 0, 2, 6, 0, 0 } }; // Start with the empty List of lists row_list start = null ; // Function creating List of Lists start = create_row_list(start, R, C, Sparse_Matrix); // Display data of List of lists print_LIL(start); } } // This code is contributed by phasing17. |
Javascript
// JavaScript program for Sparse Matrix Representation // using List Of Lists let R = 4; let C = 5; // Node to represent row - list class row_list { constructor() { this .row_number; this .link_down; this .link_right; } }; // Node to represent triples class value_list { constructor() { this .column_index; this .value; this .next; } }; // Function to create node for non - zero elements function create_value_node(data, j, z) { let temp, d; // Create new node dynamically temp = new value_list(); temp.column_index = j + 1; temp.value = data; temp.next = null ; // Connect with row list if (z.link_right == null ) z.link_right = temp; else { // d points to data list node d = z.link_right; while (d.next != null ) d = d.next; d.next = temp; } return z; } // Function to create row list function create_row_list(start, row, column, Sparse_Matrix) { // For every row, node is created for ( var i = 0; i < row; i++) { let z, r; // Create new node dynamically z = new row_list(); z.row_number = i + 1; z.link_down = null ; z.link_right = null ; if (i == 0) start = z; else { r = start; while (r.link_down != null ) r = r.link_down; r.link_down = z; } // Firstly node for row is created, // and then traversing is done in that row for ( var j = 0; j < 5; j++) { if (Sparse_Matrix[i][j] != 0) { z = create_value_node(Sparse_Matrix[i][j], j, z); } } } return start; } // Function display data of LIL function print_LIL(start) { let r; let z; r = start; // Traversing row list while (r != null ) { if (r.link_right != null ) { console.log( "row=" + r.row_number); z = r.link_right; // Traversing data list while (z != null ) { console.log( "column=" + z.column_index + " value=" + z.value); z = z.next; } } r = r.link_down; } } // Driver of the program // Assume 4x5 sparse matrix let Sparse_Matrix = [ [ 0, 0, 3, 0, 4 ], [ 0, 0, 5, 7, 0 ], [ 0, 0, 0, 0, 0 ], [ 0, 2, 6, 0, 0 ] ]; // Start with the empty List of lists let start = null ; // Function creating List of Lists start = create_row_list(start, R, C, Sparse_Matrix); // Display data of List of lists print_LIL(start); // This code is contributed by phasing17. |
row=1 column=3 value=3 column=5 value=4 row=2 column=3 value=5 column=4 value=7 row=4 column=2 value=2 column=3 value=6
Dictionary of Keys
An alternative representation of sparse matrix is Dictionary. For the key field of the dictionary, pair of row and column index is used that maps with the non – zero element of the matrix. This method saves space but sequential access of items is costly.
In C++, dictionary is defined as map class of STL(Standard Template Library). To know more about map click the link below:
Basics of map
Implementation:
CPP
// C++ program for Sparse Matrix Representation // using Dictionary #include<bits/stdc++.h> using namespace std; #define R 4 #define C 5 // Driver of the program int main() { // Assume 4x5 sparse matrix int Sparse_Matrix[R][C] = { {0 , 0 , 3 , 0 , 4 }, {0 , 0 , 5 , 7 , 0 }, {0 , 0 , 0 , 0 , 0 }, {0 , 2 , 6 , 0 , 0 } }; /* Declaration of map where first field(pair of row and column) represent key and second field represent value */ map< pair< int , int >, int > new_matrix; for ( int i = 0; i < R; i++) for ( int j = 0; j < C; j++) if (Sparse_Matrix[i][j] != 0) new_matrix[make_pair(i+1,j+1)] = Sparse_Matrix[i][j] ; int c = 0; // Iteration over map for ( auto i = new_matrix.begin(); i != new_matrix.end(); i++ ) { if (c != i->first.first) { cout << "row = " << i->first.first << endl ; c = i->first.first; } cout << "column = " << i->first.second << " " ; cout << "value = " << i->second << endl; } return 0; } |
Java
// Java program for Sparse Matrix Representation // using Dictionary import java.util.*; import java.util.concurrent.*; class GFG { static int R = 4 ; static int C = 5 ; // Driver of the program public static void main(String[] args) { // Assume 4x5 sparse matrix int [][] Sparse_Matrix = { { 0 , 0 , 3 , 0 , 4 }, { 0 , 0 , 5 , 7 , 0 }, { 0 , 0 , 0 , 0 , 0 }, { 0 , 2 , 6 , 0 , 0 } }; /* Declaration of map where first field(pair of row and column) represent key and second field represent value */ TreeMap< List<Integer>, Integer> new_matrix = new TreeMap< List<Integer>, Integer>( new Comparator<List<Integer>>() { public int compare(List<Integer> lst1, List<Integer> lst2) { if (lst1.get( 0 ) < lst2.get( 0 )) return - 1 ; if (lst1.get( 0 ) > lst2.get( 0 )) return 1 ; if (lst1.get( 1 ) < lst2.get( 1 )) return - 1 ; if (lst1.get( 1 ) > lst2.get( 1 )) return 1 ; return 0 ; } });; for ( int i = 0 ; i < R; i++) for ( int j = 0 ; j < C; j++) if (Sparse_Matrix[i][j] != 0 ) new_matrix.put(Collections.unmodifiableList(Arrays.asList(i + 1 , j + 1 )), Sparse_Matrix[i][j]); int c = 0 ; // Iteration over map for (var i : new_matrix.entrySet()) { if (c != i.getKey().get( 0 )) { System.out.println( "row = " + i.getKey().get( 0 ) ) ; c = i.getKey().get( 0 ); } System.out.print( "column = " + i.getKey().get( 1 ) + " " ); System.out.println( "value = " + i.getValue()); } } } // This code is contributed by phasing17. |
Python3
# Python program for Sparse Matrix Representation # using Dictionary R = 4 C = 5 # Driver of the program # Assume 4x5 sparse matrix Sparse_Matrix = [[ 0 , 0 , 3 , 0 , 4 ] , [ 0 , 0 , 5 , 7 , 0 ] , [ 0 , 0 , 0 , 0 , 0 ] , [ 0 , 2 , 6 , 0 , 0 ]] ''' Declaration of map where first field(pair of row and column) represent key and second field represent value ''' new_matrix = {} for i in range (R): for j in range (C): if (Sparse_Matrix[i][j] ! = 0 ): new_matrix[(i + 1 , j + 1 )] = Sparse_Matrix[i][j] c = 0 # Iteration over map for i in new_matrix: if (c ! = i[ 0 ]): print ( "row =" , i[ 0 ]) c = i[ 0 ] print ( "column =" , i[ 1 ], end = " " ) print ( "value =" , new_matrix[i]) # This code is contributed by Shubham Singh |
C#
// C# program for Sparse Matrix Representation // using Dictionary using System; using System.Collections.Generic; class GFG { static int R = 4; static int C = 5; // Driver of the program public static void Main( string [] args) { // Assume 4x5 sparse matrix int [, ] Sparse_Matrix = { {0 , 0 , 3 , 0 , 4 }, {0 , 0 , 5 , 7 , 0 }, {0 , 0 , 0 , 0 , 0 }, {0 , 2 , 6 , 0 , 0 } }; /* Declaration of map where first field(pair of row and column) represent key and second field represent value */ Dictionary< Tuple< int , int >, int > new_matrix = new Dictionary< Tuple< int , int >, int >(); for ( int i = 0; i < R; i++) for ( int j = 0; j < C; j++) if (Sparse_Matrix[i, j] != 0) new_matrix[Tuple.Create(i+1,j+1)] = Sparse_Matrix[i,j] ; int c = 0; // Iteration over map foreach ( var i in new_matrix) { if (c != i.Key.Item1) { Console.WriteLine( "row = " + i.Key.Item1) ; c = i.Key.Item1; } Console.Write( "column = " + i.Key.Item2 + " " ); Console.WriteLine( "value = " + i.Value); } } } // This code is contributed by phasing17. |
Javascript
// JS program for Sparse Matrix Representation // using Dictionary let R = 4 let C = 5 // Driver of the program // Assume 4x5 sparse matrix let Sparse_Matrix=[[0 , 0 , 3 , 0 , 4] , [0 , 0 , 5 , 7 , 0] , [0 , 0 , 0 , 0 , 0] , [0 , 2 , 6 , 0 , 0]] // Declaration of map where first field(pair of // row and column) represent key and second // field represent value ''' let new_matrix = {} for ( var i = 0; i < R; i++) for ( var j = 0; j < C; j++) if (Sparse_Matrix[i][j] != 0) new_matrix[ i + 1 + "#" + j + 1] = Sparse_Matrix[i][j] let c = 0 // Iteration over map for ( let [key, val] of Object.entries(new_matrix)) { let i = key.split( "#" ) if (c != i[0]) { console.log( "row =" , i[0]) c = i[0] } console.log( "column = " + i[1] + " value = " + val) } // This code is contributed by phasing17 |
row = 1 column = 3 value = 3 column = 5 value = 4 row = 2 column = 3 value = 5 column = 4 value = 7 row = 4 column = 2 value = 2 column = 3 value = 6
Time Complexity: O(R*C)
Auxiliary Space: O(R*C)
This article is contributed by Akash Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Login to comment...