【发布时间】:2018-04-05 17:15:54
【问题描述】:
我想编写一个程序来查找拉丁方的所有解决方案。我想使用回溯来做到这一点。我使用类似的方法解决了 n-queens 问题并且它有效。 此代码仅找到第一个解决方案,并且不会回溯。
public static boolean isSafe(int[][] board, int row, int col) {
for(int i = 0; i < board.length; i++) {
if(row != i) {
if(board[i][col] == board[row][col]) return false;
}
if(col != i) {
if(board[row][i] == board[row][col]) return false;
}
}
return true;
}
public static void enumerate(int N) {
int[][] board = new int[N][N];
enumerate(board, 0, 0);
}
public static void enumerate(int[][] board, int row, int col) {
int boardSize = board.length;
if (col == boardSize ) {
System.out.println();
print(board);
SaveToFile.saveSquare("Latin", "BT", board, boardSize);
}
else {
for (int i = 1; i <= boardSize; i++) {
board[row][col] = i;
if (isSafe(board, row, col)) {
if(row+1 == boardSize) {
enumerate(board, 0, col+1);
}
else {
enumerate(board, row+1, col);
}
}
}
}
}
public static void print(int[][] board) {
for(int i=0; i<board.length;i++) {
for(int j=0; j<board.length; j++) {
System.out.print(" "+board[i][j]+" ");
}
System.out.println();
}
System.out.println();
}
public static void main(String[] args) {
for(int i = 2; i <=2; i++) {
SaveToFile.createFile("Latin", "BT", i);
enumerate(i);
}
}
我知道我的代码看起来很糟糕,但我稍后会重构它;) 感谢您的帮助:)
【问题讨论】:
-
无关:我知道我的代码看起来很糟糕 ...但你认为让其他人阅读它是礼貌的吗?好吧,如果您花更多时间编写您理解的代码,您是否认为您需要其他人来告诉您编写的代码是(不是)在做什么?但说真的:这还不错。我在这里看到了更糟糕的新手代码;-)
-
main中的循环不会循环太多。这是有意的吗? -
我 100% 同意你的评论,但我不得不写点东西,因为没有它我无法添加这篇文章;)
-
你不应该有时重置
board[row][col]吗?您将其设置为i,然后该值保持不变。 -
@arndtJonasson 在这里我只测试一个值的程序。通常我用它来运行不同值的程序。
标签: java recursion backtracking latin-square