Search code examples
javaarraysmatrixmultidimensional-arrayruntime-error

Run time error message in set matrix zero code in Java language


I got this error when I run this code and I don't know how to solve this issue

Runtime Error Message:

WARNING: A command line option has enabled the Security Manager

WARNING: The Security Manager is deprecated and will be removed in a future release

java.lang.ArrayIndexOutOfBoundsException: Index 1 out of bounds for length 1

at line 14, Solution.setZeroes

at line 54, DriverSolution.helper

at line 84, Driver.main

Last executed input:

[[1],[0]]

The Code is:

class Solution {
public void setZeroes(int[][] matrix) {
        boolean firstColumnZero = false;
        boolean firstRowZero = false;
        
        for(int i=0;i<matrix.length;i++){
            if(matrix[i][0]==0){
                firstColumnZero = true;
                break;
            }
        }
        
        for(int i=0;i<matrix.length;i++){
            if(matrix[0][i]==0){
                firstRowZero = true;
                break;
            }
        }
        for(int i=0;i<matrix.length;i++){
            for(int j=0;j<matrix[0].length;j++){
                if(matrix[i][j]==0){
                    matrix[i][0]=0;
                    matrix[0][j]=0;
                }
            }
        }
            
        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;
                }
            }
        }
        
        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;
        }
    }
}

}

The output is :

Accepted

Runtime: 0 ms

Your input

[[1,1,1],[1,0,1],[1,1,1]]

[[0,1,2,0],[3,4,5,2],[1,3,1,5]]

Output

[[1,0,1],[0,0,0],[1,0,1]]

[[0,0,0,0],[0,4,5,0],[0,3,1,0]]

Expected

[[1,0,1],[0,0,0],[1,0,1]]

[[0,0,0,0],[0,4,5,0],[0,3,1,0]]


Solution

  • This code could be your problem:

    for ( int i = 0; i < matrix.length; i++ )
    {
        if ( matrix[0][i] == 0 )
        {
            firstRowZero = true;
            break;
        }
    }
    

    You will want to change the for statement to this:

    for ( int i = 0; i < matrix[0].length; i++ )