简体   繁体   中英

How to initialize static array variable array in Java

I have something like this in my code for a Dynamic Programming problem.

class Solution 
{
    
    static int dp[][] = new int[1000][1000];
    static int someMethod(int a, int b) {
        // use dp[][] somewhere here
        // some recursion statements
        someMethod(a-x,b-y);
    }
}

I want to initialize all values in dp with -1 instead of 0 . Standard initialization inside method isn't an option because it uses recursion to make multiple calls.

Solution goes into an online judging tool so can't really config anything too. Any plain code solution will be appreciated.

You said:

I want to initialize all values in dp with -1 instead of 0.

Call a static method that creates, populates, and returns the needed array.

class Solution 
{
    static int[][] dp = Solution.makeArray() ;
    static int[][] makeArray() {
        int limit = 1_000 ;
        int[][] a = new int[ limit ][ limit ] ;
        for ( row = 0; row < limit ; row ++) {
            for ( column = 0; column < limit ; column ++) {
                a[ row ][ column ] = -1 ;
            }
        }
        return a ;
    }
}
class Solution 
{
    
    static int dp[][];
    static {
       dp = new int[1000][1000];
       for (int[] row: dp) {
          Arrays.fill(row, -1);
       }
    }

    static int someMethod(int a, int b) {
        // use dp[][] somewhere here
        // some recursion statements
        someMethod(a-x,b-y);
    }
}

If you are required to use recursion to do this, you can do it as follows: I reduced the size of the array for demo purposes. But for a 1000 x 1000 array you may get a StackOverflow unless you modify your JVM parameters. Using Eclipse, I had to set stack size to 28 megabytes via the
java -Xss28m command.

import java.util.Arrays;

class Solution {
    
    static int dp[][] = new int[10][10];

    public static void main(String[] arg) {
        someMethod(0, 0);
        for (int[] row : dp) {
            System.out.println(Arrays.toString(row));
        }
    }

prints

[-1, -1, -1, -1, -1, -1, -1, -1, -1, -1]
[-1, -1, -1, -1, -1, -1, -1, -1, -1, -1]
[-1, -1, -1, -1, -1, -1, -1, -1, -1, -1]
[-1, -1, -1, -1, -1, -1, -1, -1, -1, -1]
[-1, -1, -1, -1, -1, -1, -1, -1, -1, -1]
[-1, -1, -1, -1, -1, -1, -1, -1, -1, -1]
[-1, -1, -1, -1, -1, -1, -1, -1, -1, -1]
[-1, -1, -1, -1, -1, -1, -1, -1, -1, -1]
[-1, -1, -1, -1, -1, -1, -1, -1, -1, -1]
[-1, -1, -1, -1, -1, -1, -1, -1, -1, -1]

The method

    static void someMethod(int a, int b) {
        if (b < dp[0].length - 1) {
            someMethod(a, b + 1);
        } else if (a < dp.length - 1) {
            someMethod(a + 1, 0);
        }
        dp[a][b] = -1;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM