Java 动态规划,两人矩阵对策
我正在编写一个由两人玩的矩阵游戏。目的是说明玩家1是否可以赢得游戏返回1,如果不是返回0。 玩家可以删除矩阵的最后一行或最后一列,但前提是该行/列中的数字之和为偶数。例如:Java 动态规划,两人矩阵对策,java,algorithm,matrix,dynamic-programming,Java,Algorithm,Matrix,Dynamic Programming,我正在编写一个由两人玩的矩阵游戏。目的是说明玩家1是否可以赢得游戏返回1,如果不是返回0。 玩家可以删除矩阵的最后一行或最后一列,但前提是该行/列中的数字之和为偶数。例如: original matrix: [1 2] [2 2] then we can subtract these matrices from this: sum row, and this becomes: [1 3] [0 0] [2 4] [1 1] su
original matrix:
[1 2]
[2 2]
then we can subtract these matrices from this:
sum row, and this becomes:
[1 3] [0 0]
[2 4] [1 1]
sum col, and this becomes:
[1 2] [0 1]
[3 4] [0 1]
现在我们可以玩这个游戏了,很明显,玩家1可以从行矩阵或列矩阵中移除。然后玩家2可以移动,最后我们可以看到在这个例子中玩家1不能赢
以下是我对该计划的实施:
我只提供假设使用行和列矩阵的方法,如果玩家1赢了,应该返回1,如果玩家1赢了,应该返回0
public static int play(int[][] rowM, int[][] colM){
int player = 1;
int[][] matrix = new int[rowM.length][colM[0].length];
for (int i = 0; i < rowM.length; i++) {
for (int j = 0; j < colM[0].length; j++) {
//if no possible move
if(rowM[i][j] == 0 && colM[i][j] == 0){
//if player 1 is playing, and losing
if(player % 2 == 1){
matrix[i][j] = 0;
player++;
}
//player 2 is losing
else{
matrix[i][j] = 1;
player++;
}
continue;
}
//if player 1 is playing
if(player % 2 == 1){
player++;
//the value in this position is even
if(rowM[i][j] == 1){
//if there is only 1 row left,
if(i == 0){
matrix[i][j] = 1;
}
else if(matrix[i-1][j] == 1){
matrix[i][j] = 1;
}
else{
matrix[i][j] = 0;
}
}
//the value in the col matrix this position is even
else if(colM[i][j] == 1){
//if there is only 1 column left,
if(j == 0){
//matrix[i][j] = 1;
matrix[i][j] = 1;
//player++;
}
else if (matrix[i][j-1] == 1){
matrix[i][j] = 1;
}
else{
matrix[i][j] = 0;
}
}
}
//player 2 is playing
else{
player++;
//the value in this position is even
if(rowM[i][j] == 1){
if(i == 0){
matrix[i][j] = 1;
}
else if(matrix[i-1][j] == 1){
matrix[i][j] = 0;
}
else{
matrix[i][j] = 1;
}
}
//the value in the col matrix this position is even
else if(colM[i][j] == 1){
if(j == 0){
matrix[i][j] = 1;
}
else if(matrix[i][j-1] == 1){
matrix[i][j] = 0;
}
else{
matrix[i][j] = 1;
}
}
}
}
}
return matrix[rowM.length-1][colM[0].length-1];
}
这给了我一个1,但它错了,应该是0。有人能帮我找到我的问题吗。这是我最后的选择,看看我做错了什么。请帮忙
这个问题与其他问题有何不同?我认为你需要重新阅读那里关于如何解决问题的评论(把事情分成小块,测试每一块)。我把它做得更小了。那个问题更大,有更多的代码和解释,所以可读。@S.N:要改进问题,请编辑问题,不要重新发布。(底部附近有一个“编辑”链接。)但我认为你得到的其他建议将比试图把这个问题塞进SO的格式更有帮助。@s.N我花了一些时间试图理解游戏规则,但仍然毫无头绪。你能给我讲讲每个玩家在原始矩阵上的一步一步的操作吗?还是对游戏规则给出更好的解释?@kiruwka请看我的例子。它是以图片的形式出现的。如果你还不明白,你可以问我更多的问题。
a matrix 2*1:
[2]
[1]