Update SetMatrixToZero.java

This commit is contained in:
anujgaud 2024-04-09 23:18:22 +05:30 committed by GitHub
parent dbd9448e99
commit 306d2da98c
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -61,64 +61,87 @@ public class SetMatrixToZero{
matrix[i][col] = 0;
}
}
}
static void setZeroesByOptimalApproach(int[][] matrix){
int rows = matrix.length;
int cols = matrix[0].length;
}
boolean firstRowZero = false;
boolean firstColZero = false;
for(int j = 0; j < cols; j++){
static boolean hasZeroInFirstRow(int[][] matrix, int cols) {
for (int j = 0; j < cols; j++) {
if (matrix[0][j] == 0) {
firstRowZero = true;
break;
return true;
}
}
return false;
}
for(int i = 0; i < rows; i++){
static boolean hasZeroInFirstCol(int[][] matrix, int rows) {
for (int i = 0; i < rows; i++) {
if (matrix[i][0] == 0) {
firstColZero = true;
break;
return true;
}
}
for(int i = 1; i < rows; i++){
for(int j = 1; j < cols; j++){
if (matrix[i][j] == 0){
return false;
}
static void markZeroesInMatrix(int[][] matrix, int rows, int cols) {
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++){
}
static void setZeroesInRows(int[][] matrix, int rows, int cols) {
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;
}
}
}
static void setZeroesInCols(int[][] matrix, int rows, int cols) {
for (int j = 1; j < cols; j++) {
if (matrix[0][j] == 0) {
for (int i = 1; i < rows; i++) {
matrix[i][j] = 0;
}
}
}
}
static void setZeroesInFirstRow(int[][] matrix, int cols) {
for (int j = 0; j < cols; j++) {
matrix[0][j] = 0;
}
}
static void setZeroesInFirstCol(int[][] matrix, int rows) {
for (int i = 0; i < rows; i++) {
matrix[i][0] = 0;
}
}
static void setZeroesByOptimalApproach(int[][] matrix) {
int rows = matrix.length;
int cols = matrix[0].length;
boolean firstRowZero = hasZeroInFirstRow(matrix, cols);
boolean firstColZero = hasZeroInFirstCol(matrix, rows);
markZeroesInMatrix(matrix, rows, cols);
setZeroesInRows(matrix, rows, cols);
setZeroesInCols(matrix, rows, cols);
if (firstRowZero) {
setZeroesInFirstRow(matrix, cols);
}
if (firstColZero) {
setZeroesInFirstCol(matrix, rows);
}
}
}