【发布时间】:2015-09-22 19:27:21
【问题描述】:
如果我尝试从求解函数之外的 LinkedList “solvedBords”中读取保存在solvedBords 中的二维数组“board”中的所有值。
但在“solved”函数中,保存在solvedBords中的二维数组“board”中的所有值都是完全准确的。
这是由于递归吗?任何解释将不胜感激
主类
public class main {
public static void main(String[] arg){
testQueen N = new testQueen();
}
}
测试类
import javax.swing.*;
import java.util.LinkedList;
public class testQueen {
private int[][] board;
private LinkedList<int[][]> solvedBords = new LinkedList<>();
private static int boardSize = 0;
testQueen() {
boardSize = 8;
board = new int[boardSize][boardSize];
start();
}
void start() {
solve(0);
System.out.println("solvedBords = " + solvedBords.size());
while (!solvedBords.isEmpty()) {
System.out.println("this is in the start funktion");
printBord(solvedBords.pop());
System.out.println("");
}
}
void solve(int row) {
if (row == boardSize) {
System.out.println("this is in the solve function: ");
printBord(board);
System.out.println("");
solvedBords.add(board.clone()); // 2d array “board” that is saved in
// solvedBords
/*
* System.out.println("solvedBords = " + solvedBords.size());
* while(!solvedBords.isEmpty()){ printBord(solvedBords.pop());
* System.out.println(""); }
*/
return;
}
for (int colum = 0; colum < boardSize; colum++) {
if (validMove(row, colum)) {
paceQueen(row, colum, 0);
solve(row + 1);
paceQueen(row, colum, 1);
}
}
}
boolean validMove(int x, int y) {
for (int i = 0; i < boardSize; i++) {
if (get(x, i) > 0) {
return false;
}
if (get(i, y) > 0) {
return false;
}
if (get(x - i, y - i) > 0) {
return false;
}
if (get(x - i, y + i) > 0) {
return false;
}
if (get(x + i, y - i) > 0) {
return false;
}
if (get(x + i, y + i) > 0) {
return false;
}
}
return true;
}
/**
*
* if type == 1 the queen is going to be placed in row x and column y
*
* else if type == 0 the queen is going to be removed from row x column y
*
* @param x
* is the row
* @param y
* is the column
* @param type
* is 0 or 1
*/
void paceQueen(int x, int y, int type) {
if (type == 0) {
board[x][y] = 1;
} else if (type == 1) {
board[x][y] = 0;
}
}
int get(int x, int y) {
if (x < 0 || y < 0 || x >= boardSize || y >= boardSize) {
return -1;
}
return board[x][y];
}
void printBord(int[][] board) {
for (int i = 0; i < boardSize; i++) {
for (int j = 0; j < boardSize; j++) {
if (board[i][j] > 0) {
System.out.print("[1]");
} else if (board[i][j] == 0) {
System.out.print("[0]");
}
}
System.out.println();
}
}
}
【问题讨论】:
-
你能修正你的缩进吗?
-
尽力修复,无法粘贴代码。
-
您的帖子不可读,请使用标点符号和正确的语法。
标签: java arrays recursion multidimensional-array linked-list