Simple solution by storing indices


  • 0
    R
    public void setZeroes(int[][] matrix) {
            int m = matrix.length;
            int n = matrix[0].length;
            
            ArrayList<Integer> zi = new ArrayList<Integer>();
            
            for(int i=0; i < m; i++){
                for(int j=0; j < n; j++){
                    if(matrix[i][j] == 0){
                      int zival = i*n + j;  
                      zi.add(zival);
                    } 
                }
            }
            
            for(int zival : zi){
                int i = zival / n;
                int j = zival % n;
                
                for(int k=0; k < n; k++){
                    matrix[i][k] = 0;
                }
                
                for(int k=0; k < m; k++){
                    matrix[k][j] = 0;
                }
            }
        }
    

Log in to reply
 

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