I'm new to coding and I'm currently trying to solve this question: https://leetcode.com/problems/set-matrix-zeroes/
Code:
class Solution {
public void setZeroes(int[][] matrix) {
int [][] arr = matrix;
for(int m=0;m<matrix.length;m++) {
for(int n = 0;n<matrix[m].length;n++) {
if(matrix[m][n] == 0) {
//loop 1
for(int i = 0; i<matrix.length;i++) {
arr[i][n] = 0;
}
//loop 2
for(int i = 0; i<matrix[m].length;i++) {
arr[m][i] = 0;
}
}
}
}
matrix = arr;
}
}
Working code:
class Solution {
public void setZeroes(int[][] matrix) {
//declaring new 2D array
int[][] arr = new int[matrix.length][matrix[0].length];
//giving values to new 2D array (copying matrix)
for(int i = 0; i<matrix.length;i++) {
for(int j = 0; j<matrix[i].length;j++) {
arr[i][j] = matrix[i][j];
}
}
for(int m=0;m<matrix.length;m++) {
for(int n = 0;n<matrix[m].length;n++) {
if(matrix[m][n] == 0) {
for(int i = 0; i<matrix.length;i++) {
arr[i][n] = 0;
}
for(int i = 0; i<matrix[m].length;i++) {
arr[m][i] = 0;
}
}
}
}
for(int i = 0; i<matrix.length;i++) {
for(int j = 0; j<matrix[i].length;j++) {
matrix[i][j] = arr[i][j];
}
}
}
}
The problem I'm having is that the for loops are working fine separately, but when I run them together, they aren't working. If you remove loop 1, the loop 2 works fine.
The first for loop (loop 1) adds '0' vertically wherever they belong, and the second for loop (loop 2) adds '0' horizontally like its supposed to. But together, they don't work. What's the issue that I'm having?