您如何计算数独中某个空格处的有效数字列表?

问题描述 投票:0回答:1

我正在尝试让一种方法返回允许在任何给定位置输入的数字,但是允许值数组包含不允许的值。Note-我不能使用任何软件包或香草java以外的任何东西(尤其是[[不能使用ArrayList-只是说这是因为它被建议给我)这是我的代码:

public int[] getAllowedValues(int row, int col){ int[] allowedValues = new int[9]; for(int i = 0; i < 9; i++){ allowedValues[i] = i; } for(int i = 0; i < 9; i++){ if(!(board[i][col] == 0)){ allowedValues[board[i][col]] = 0; //anything with a 0 is illegal, with number means that number is legal } if(!(board[row][i] == 0)){ allowedValues[board[row][i]] = 0; //anything with a 0 is illegal, with number means that number is legal } } int rowStart = 0; //rowStart is the top left coord of box the number is in if(row <= 3){ rowStart = 1; } else if (row <= 6){ rowStart = 4; } else if (row <= 9){ rowStart = 7; } int colStart = 0; //colStart is the top left coord of the box the number is in if(col <= 3){ colStart = 1; } else if (col <= 6){ colStart = 4; } else if (col <= 9){ colStart = 7; } for(int i = rowStart; i < rowStart + 3; i++){ for(int j = colStart; j < colStart + 3; j++){ if(!(board[i-1][j-1] == 0)){ allowedValues[board[i-1][j-1]] = 0; } } } for(int i = row; i < 9; i++){ for(int j = col; j < 9; j++){ if((board[i][j] == 0)){ allowedValues[board[i][j]] = 0; } if((board[j][i] == 0)){ allowedValues[board[j][i]] = 0; } } } return allowedValues; }
由于某些原因,允许的数字包括同一列/行/正方形中的数字,它会有所不同...非常感谢您的帮助。 
java
1个回答
0
投票
双方

这是作业,您的作业应包括学习调试自己的代码。 (这是一项重要技能!)

关于这一点,我强烈建议您阅读Eric Lippert在"How to debug small programs"上的博客文章。并且

practice

使用他描述的技术。您说:

...无法使用ArrayList-只是说

因为有人向我建议

这不是一个好建议(IMO)。在您的程序中(即鉴于程序需要执行的操作),int[]是一个不错的选择。您只是在使用数组的方式上犯了一个错误。


主要

您尝试的解决方案的问题是Sudoko拼图中的数字从1到9,但是allowedValues数组的数组索引从0到8。因此,例如:

allowedValues[board[i][col]] = 0;

将错误的数组元素设置为零。您应该能够弄清楚如何解决此问题……以及其他您犯了相同错误的地方。
© www.soinside.com 2019 - 2024. All rights reserved.