Search
 
SCRIPT & CODE EXAMPLE
 

JAVA

set matrix zeros

public class Solution {
    public void setZeroes(int[][] matrix) {
        boolean firstRowZero = false;
        boolean firstColumnZero = false;
 
        //set first row and column zero or not
        for(int i=0; i<matrix.length; i++){
            if(matrix[i][0] == 0){
                firstColumnZero = true;
                break;
            }
        }
 
        for(int i=0; i<matrix[0].length; i++){
            if(matrix[0][i] == 0){
                firstRowZero = true;
                break;
            }
        }
 
        //mark zeros on first row and column
        for(int i=1; i<matrix.length; i++){
            for(int j=1; j<matrix[0].length; j++){
                if(matrix[i][j] == 0){
                   matrix[i][0] = 0;
                   matrix[0][j] = 0;
                }
            }
        }
 
        //use mark to set elements
        for(int i=1; i<matrix.length; i++){
            for(int j=1; j<matrix[0].length; j++){
                if(matrix[i][0] == 0 || matrix[0][j] == 0){
                   matrix[i][j] = 0;
                }
            }
        }
 
        //set first column and row
        if(firstColumnZero){
            for(int i=0; i<matrix.length; i++)
                matrix[i][0] = 0;
        }
 
        if(firstRowZero){
            for(int i=0; i<matrix[0].length; i++)
                matrix[0][i] = 0;
        }
 
    }
}
Comment

PREVIOUS NEXT
Code Example
Java :: java cannot find file path 
Java :: convert class to java 
Java :: latest android version 
Java :: array find max in java 
Java :: how to read text file as variable in java 
Java :: how to create an entry in java 
Java :: what are method in java 
Java :: java queue implementation 
Java :: create hashmap in java 
Java :: android dialog modal 
Java :: char array to string in java 
Java :: how to addin java 
Java :: java double to float 
Java :: android generate random int 
Java :: abstract method declaration 
Java :: radix sort java 
Java :: thread implements runnable 
Java :: java array of array 
Java :: separateur JMenu swing java 
Java :: System.out.println("j= 6"); 
Java :: startactivity not working in android adapter 
Java :: how to covert array into a char 
Java :: string to char 
Java :: how to get start char in string in java 
Java :: observer pattern java 
Java :: Unexpected end of file in android studio activity main.xml 
Java :: java array object 
Java :: JSONObject append 
Java :: difference between linkedlist and arraylist 
Java :: final method and abstract method 
ADD CONTENT
Topic
Content
Source link
Name
3+7 =