import
java.util.HashMap;
class
SparseMatrix {
private
final
int
rows;
private
final
int
cols;
private
final
HashMap<Integer, HashMap<Integer, Integer>> matrixElements;
public
SparseMatrix(
int
rows,
int
cols) {
this
.rows = rows;
this
.cols = cols;
this
.matrixElements =
new
HashMap<>();
}
public
void
insert(
int
row,
int
col,
int
value) {
if
(row >=
0
&& row < rows && col >=
0
&& col < cols)
{
matrixElements.computeIfAbsent(row, k ->
new
HashMap<>()).put(col, value);
}
else
{
System.out.println(
"Invalid row or column index"
);
}
}
public
int
get(
int
row,
int
col)
{
return
matrixElements.getOrDefault(row,
new
HashMap<>()).getOrDefault(col,
0
);
}
public
void
print()
{
for
(
int
i =
0
; i < rows; i++)
{
for
(
int
j =
0
; j < cols; j++)
{
System.out.print(get(i, j) +
" "
);
}
System.out.println();
}
}
public
SparseMatrix add(SparseMatrix otherMatrix)
{
if
(
this
.rows != otherMatrix.rows ||
this
.cols != otherMatrix.cols)
{
System.out.println(
"Matrix dimensions don't match for addition."
);
return
null
;
}
SparseMatrix resultMatrix =
new
SparseMatrix(rows, cols);
for
(
int
i =
0
; i < rows; i++)
{
for
(
int
j =
0
; j < cols; j++)
{
int
sum =
this
.get(i, j) + otherMatrix.get(i, j);
if
(sum !=
0
) {
resultMatrix.insert(i, j, sum);
}
}
}
return
resultMatrix;
}
}
public
class
Main
{
public
static
void
main(String[] args)
{
SparseMatrix matrix1 =
new
SparseMatrix(
3
,
3
);
matrix1.insert(
0
,
0
,
1
);
matrix1.insert(
0
,
2
,
2
);
matrix1.insert(
1
,
1
,
3
);
SparseMatrix matrix2 =
new
SparseMatrix(
3
,
3
);
matrix2.insert(
0
,
0
,
4
);
matrix2.insert(
0
,
2
,
5
);
matrix2.insert(
1
,
1
,
6
);
SparseMatrix resultMatrix = matrix1.add(matrix2);
System.out.println(
"Matrix 1:"
);
matrix1.print();
System.out.println(
"\nMatrix 2:"
);
matrix2.print();
System.out.println(
"\nThe Resultant Matrix (Sum of Matrix 1 and Matrix 2): "
);
if
(resultMatrix !=
null
) {
resultMatrix.print();
}
}
}