From 2922f0619f280b23209dafe18abc49015d206b3a Mon Sep 17 00:00:00 2001 From: anujgaud <146576725+anujgaud@users.noreply.github.com> Date: Sat, 16 Mar 2024 23:21:47 +0530 Subject: [PATCH] Create SetMatrixToZero.java --- .../matrixToZero/SetMatrixToZero.java | 115 ++++++++++++++++++ 1 file changed, 115 insertions(+) create mode 100644 core-java-modules/core-java-arrays-operations-advanced-2/src/main/java/com/baeldung/matrixToZero/SetMatrixToZero.java diff --git a/core-java-modules/core-java-arrays-operations-advanced-2/src/main/java/com/baeldung/matrixToZero/SetMatrixToZero.java b/core-java-modules/core-java-arrays-operations-advanced-2/src/main/java/com/baeldung/matrixToZero/SetMatrixToZero.java new file mode 100644 index 0000000000..d195698299 --- /dev/null +++ b/core-java-modules/core-java-arrays-operations-advanced-2/src/main/java/com/baeldung/matrixToZero/SetMatrixToZero.java @@ -0,0 +1,115 @@ +package com.baeldung.matrixToZero; + +import java.util.*; + +public class SetMatrixToZero{ + static void setZeroesBruteForce(int[][] matrix) { + int row = matrix.length; + int col = matrix[0].length; + int [][] result = new int[row][col]; + + for(int i = 0; i rowSet = new HashSet<>(); + Set colSet = new HashSet<>(); + + for(int i = 0; i < rows; i++){ + for(int j = 0; j < cols; j++){ + if (matrix[i][j] == 0){ + rowSet.add(i); + colSet.add(j); + } + } + } + for(int row: rowSet){ + for(int j = 0; j < cols; j++){ + matrix[row][j] = 0; + } + } + for(int col: colSet) { + for(int i = 0; i < rows; i++){ + matrix[i][col] = 0; + } + } + } + static void setZeroesOptimized(int[][] matrix){ + int rows = matrix.length; + int cols = matrix[0].length; + + boolean firstRowZero = false; + boolean firstColZero = false; + + for(int j = 0; j < cols; j++){ + if (matrix[0][j] == 0) { + firstRowZero = true; + break; + } + } + + for(int i = 0; i < rows; i++){ + if (matrix[i][0] == 0) { + firstColZero = true; + break; + } + } + for(int i = 1; i < rows; i++){ + for(int j = 1; j < cols; j++){ + if (matrix[i][j] == 0){ + matrix[i][0] = 0; + matrix[0][j] = 0; + } + } + } + for(int i = 1; i < rows; i++){ + if(matrix[i][0] == 0){ + for(int j = 1; j < cols; j++){ + matrix[i][j] = 0; + } + } + } + for(int j = 1; j < cols; j++){ + if(matrix[0][j] == 0) { + for(int i = 1; i < rows; i++){ + matrix[i][j] = 0; + } + } + } + if(firstRowZero){ + for(int j = 0; j < cols; j++){ + matrix[0][j] = 0; + } + } + if(firstColZero){ + for(int i = 0; i < rows; i++){ + matrix[i][0] = 0; + } + } + } +}