Where did I go wrong with my code?


  • 0
    H

    I intended to discover the first 0 value and use its row and column as marker. But I cannot find out where did I go wrong with this design.

    public class Solution {
    public void setZeroes(int[][] matrix) {
        int m = matrix.length;
        if(m==0)return;
        int n = matrix[0].length;
        if(n==0)return;
        boolean discover = false;
        int row = -1;
        int col = -1;
        for(int i=0;i<m;i++){
            for(int j=0;j<n;j++){
                if(matrix[i][j]==0 && discover==false){
                    discover = true;
                    row = i;
                    col = j;
                }
                else if(matrix[i][j]==0 && discover==true){
                    matrix[row][j]=0;
                    matrix[i][col]=0;
                }
            }
        }
        if(discover==false) return;
        for(int i=0;i<m;i++){
            for(int j=0;j<n;j++){
                if(matrix[i][col]==0 || matrix[row][j]==0){
                    matrix[i][j]=0;
                }
            }
        }
    }
    

    }

    Test case:

    Input: [[0,0,0,5],[4,3,1,4],[0,1,1,4],[1,2,1,3],[0,0,1,1]]
    Output: [[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]]
    Expected: [[0,0,0,0],[0,0,0,4],[0,0,0,0],[0,0,0,3],[0,0,0,0]]


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.