3
memo array is reinitialized to 0爲什麼我的備忘錄數組被初始化爲0 java?
我不明白爲什麼我的備忘錄被設置爲0再次,即使我初始化爲-1,它保持了備忘錄重置爲0。下面的代碼一直稱這是自己的,但在堆棧的第一個層次,備忘錄被初始化爲0
import java.util.Arrays;
public class RGBTree {
public static void main(String[] args) {
RGBTree rgb = new RGBTree();
String[] G =
{"..B.BB...RB..","......R..B.G.",
"B.......BB...",".......R...G.",
"B....GRB..R..","B...G.RG.R...",
".R..RR..B.RB.","...RBG...G...",
"..B...B......","RBB..R.G....R",
"B...R.R......",".G.G..B.....R",".........R.R."};
System.out.println(rgb.exist(G));
}
public String exist(String[] G) {
int[][][][] memo = new int[(1 << 13)][13][13][13];
int n = G.length;
int k = (n - 1)/3;
for (int i = 0; i < 1 << 13; i++) {
for (int j = 0; j < 13; j++) {
for (int l = 0; l < 13; l++) {
for (int m = 0; m < 13; m++) {
memo[i][j][k][l] = -1;
}
}
}
}
return (f(n, 1, k, 0, 0, 0, G, memo)) ? "Exist" : "Does not";
}
private boolean f(int v, int mask, int k, int r, int g, int b, String[] graph, int[][][][]memo) {
boolean res = false;
if (memo[mask][r][g][b] != -1) {
res = memo[mask][r][g][b] == 1 ? true : false;
} else {
if (r == k && g == k && b == k) {
res = true;
}
for (int i = 0; i < v; i++) {
if (((mask & (1 << i)) == 1)) {
for (int j = 0; j < v; j++) {
if ((mask & (1 << j)) == 0 && graph[i].charAt(j) != '.') {
int nr = r, ng = g, nb = b;
char c = graph[i].charAt(j);
switch (c) {
case 'R':
nr++;
break;
case 'G':
ng++;
break;
case 'B':
nb++;
break;
}
if (nr <= k && ng <= k && nb <= k) {
res |= f(v, mask | (1 << j), k, nr, ng, nb, graph, memo);
}
}
}
}
}
memo[mask][r][g][b] = res ? 1 : 2;
}
return res;
}
}
哇,我花了幾個小時弄清楚我犯錯的地方,並且感到困惑。我非常感謝你的回覆,現在它很有用,謝謝 –