My easy java solution beats 90% in runtime, if someone can improve it to make the structure more clear, pls let me know!


  • 0

    public class Solution {
    public void setZeroes(int[][] matrix) {

        int m = matrix.length; //number of row
        int n = matrix[0].length; //number of column
        boolean fr = false, fc = false;
        
        for(int i = 1; i < n; i++) { //matrix[0][0] not included, will be considered in another senario
            if(matrix[0][i] == 0)
            fr = true;
        }
        
        //System.out.println(m);
        //System.out.println(n);
        for(int j = 1; j < m; j++) {
            if(matrix[j][0] == 0)
            fc = true;
        }
        
        for(int i = 1; i < n; i++) {
            for(int j = 1; j < m; j++) {
                if(matrix[j][i] == 0) {
                    matrix[j][0] = 0;
                    matrix[0][i] = 0;
                }
            }
        }
        
        for(int i = 1; i < n; i++) { //matrix[0][0] is not included, otherwise if matrix[0][0] == 0, each element is this 
            if(matrix[0][i] == 0) {  //matrix will be set to 0
                for(int j = 0; j < m; j++) {
                    matrix[j][i] = 0;
                }
            }
        }
        
        for(int j = 1; j < m; j++) {
            if(matrix[j][0] == 0) {
                for(int i = 0; i < n; i++) {
                    matrix[j][i] = 0;
                }
            }
        }
        
        if(matrix[0][0] == 0) {
            for(int i = 0; i < n; i++)
                matrix[0][i] = 0;
            for(int j = 0; j < m; j++)
                matrix[j][0] = 0;
        }
        
        if(fr == true) {
            for(int i = 0; i < n; i++) {
                matrix[0][i] = 0;
            }
        }
        
        if(fc == true) {
            for(int j = 0; j < m; j++) {
                matrix[j][0] = 0;
            }
        }
    }
    

    }


Log in to reply
 

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