[英]Java: Trouble when using BFS to find a shortest path
階級狀態:
import java.util.Arrays;
public class State {
private int data[][];
public int[][] getData() {
return data;
}
public void setData(int[][] data) {
this.data = data;
}
public void swap(int row1, int col1, int row2, int col2){
int temp = this.data[row1][col1];
this.data[row1][col1] = this.data[row2][col2];
this.data[row2][col2] = temp;
}
public State copyState() {
int height = this.data.length;
int width = this.data[0].length;
int[][] temp = new int[height][width];
for (int i = 0; i < height; i++) {
for(int j=0; j< width; j++){
temp[i][j] = this.data[i][j];
}
}
State target = new State(temp);
return target;
}
public State(int[][] data) {
super();
this.data = data;
}
}
類節點:
public class Node {
private State state;
private Node parent;
private ArrayList<Node> children;
public Node(State state){
this.state = state;
parent = null;
children = new ArrayList<>();
}
public State getState() {
return state;
}
public void setState(State state) {
this.state = state;
}
public Node getParent() {
return parent;
}
public void setParent(Node parent) {
this.parent = parent;
}
public ArrayList<Node> getChildren() {
return children;
}
public void addChild(Node node){
node.setParent(this);
this.children.add(node);
}
public ArrayList<Node> returnSuccessor(){ // generate all possible moves(has been tested - work well)
ArrayList<Node> result = new ArrayList<>();
int[][] matrix = this.getState().getData();
int row = matrix.length;
int col = matrix[0].length;
int rowX = 0;
int colX = 0;
for(int i=0; i<row; i++){
for(int j=0; j<col; j++){
if ( matrix[i][j] == 0) {
rowX = i;
colX = j;
}
}
}
if( (colX-1) >= 0 ){
State temp = this.getState().copyState();
temp.swap(rowX, colX, rowX, colX-1);
Node left = new Node(temp);
result.add(left);
}
if ( (colX+1) < col ){
State temp = this.getState().copyState();
temp.swap(rowX, colX, rowX, colX+1);
Node right = new Node(temp);
result.add(right);
}
if ( (rowX-1) >= 0 ){
State temp = this.getState().copyState();
temp.swap(rowX, colX, rowX-1, colX);
Node top = new Node(temp);
result.add(top);
}
if ( (rowX+1) < row ){
State temp = this.getState().copyState();
temp.swap(rowX, colX, rowX+1, colX);
Node down = new Node(temp);
result.add(down);
}
return result;
}
public void printState(){
System.out.println(Arrays.deepToString(this.getState().getData()));
}
public boolean equal(Node node){ // check whether 2 nodes are the same
return Arrays.deepEquals(this.getState().getData(), node.getState().getData());
}
public boolean checkTree(Node node){ // check whether a node has been added into the tree or not
if (this.equal(node)) {
return true;
}
ArrayList<Node> children = this.getChildren();
boolean result = false;
if (children.size() > 0){
for(int i=0; result == false && i< children.size(); i++){
result = children.get(i).checkTree(node);
}
}
return result;
}
}
班級主要:
public class main {
public static void BFS(Node root, Node goal) throws InterruptedException{
Queue<Node> queue = new LinkedList<Node>();
queue.add(root);
while(queue.size()>0){
Node temp = queue.poll();
if (temp.equal(goal)) {
goal.setParent(temp.getParent());
break;
}
else{
ArrayList<Node> successor = temp.returnSuccessor();
for(int i=0; i< successor.size(); i++){
boolean check = root.checkTree(successor.get(i));
if (check == false){
queue.add(successor.get(i));
temp.addChild(successor.get(i));
}
}
}
}
}
public static void main(String[] args) throws InterruptedException {
int[][] initialState = { {2,1}, {3,0} };
int[][] goalState = { {0,1}, {2,3} };
Node root = new Node(new State(initialState));
Node goal = new Node(new State(goalState));
BFS(root,goal);
Node temp = goal;
if(temp.getParent() == null){
System.out.println("There is no such a way to go from the initial state to the goal state");
}
else{
ArrayList<Node> listSteps = new ArrayList<>();
while(temp != null){
listSteps.add(temp);
temp = temp.getParent();
}
for (int i=listSteps.size()-1; i>=0; i--){
listSteps.get(i).printState();
Thread.sleep(1000);
}
int numSteps = listSteps.size()-1;
System.out.println("Number of steps: " + numSteps);
}
}
我想找到從初始狀態到目標狀態的最短路徑(幾乎與n-puzzle游戲相同)
當我嘗試使用2x2大小的拼圖作為輸入運行我的程序時,它運行良好。
例如輸入:
int[][] initialState = { {2,1}, {3,0} };
int[][] goalState = { {0,1}, {2,3} };
結果將是:
[[2, 1], [3, 0]]
[[2, 1], [0, 3]]
[[0, 1], [2, 3]]
Number of steps: 2
但是,它有一個nxn大小的無限循環(n> 2)
樣本輸入:
int[][] initialState = { {7,2,4}, {5,0,6}, {8,3,1} };
int[][] goalState = { {0,1,2}, {3,4,5}, {6,7,8} };
它不斷在DFS方法中將節點添加到隊列中
這讓我感到困惑,因為類Node中的方法checkTree已被編寫,目的是避免在生成狀態時可能發生的循環。
有人能搞清楚我的錯誤是什么嗎?
遲到的答案,但我希望它可以幫助某人:
發布的代碼中的基本問題是這些行:
for(int i=0; i<row; i++){
for(int j=0; j<col; j++){
if ( matrix[i][j] == 0) {
rowX = i;
colX = j;
}
}
}
這導致只檢查值為0的元素(狀態數據)中的“后繼者”或鄰居。您需要檢查所有元素的鄰居。 請注意代碼中的注釋:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.Set;
public class Main {
public static void BFS(Node root, Node goal) throws InterruptedException{
Queue<Node> queue = new LinkedList<>();
Set<Node> visited = new HashSet<>(); //**use to flow which nodes were tested
queue.add(root);
while(queue.size()>0){
Node temp = queue.poll();
if (temp.equals(goal)) {
goal.setParent(temp.getParent());
break;
}
else{
List<Node> successor = temp.returnSuccessor();
for(int i=0; i< successor.size(); i++){
//** made redundant by using visited boolean check = root.checkTree(successor.get(i));
Node node = successor.get(i);
if (visited.add(node)){ //** successful add indicates it was not visited before
queue.add(node);
temp.addChild(node);
}
}
}
}
}
public static void main(String[] args) throws InterruptedException {
int[][] initialState = { {0,1}, {2,3}, {4,5} };
int[][] goalState = {{3,4}, {5,0}, {1,2}};
Node root = new Node(new State(initialState));
Node goal = new Node(new State(goalState));
BFS(root,goal);
if(goal.getParent() == null){
System.out.println("There is no such a way to go from the initial state to the goal state");
}
else{
ArrayList<Node> listSteps = new ArrayList<>();
while(goal != null){
listSteps.add(goal);
goal = goal.getParent();
}
for (int i=listSteps.size()-1; i>=0; i--){
System.out.println(listSteps.get(i));
}
int numSteps = listSteps.size()-1;
System.out.println("Number of steps: " + numSteps);
}
}
}
class State {
private int data[][];
public int[][] getData() { return data;}
public void setData(int[][] data) { this.data = data; }
public void swap(int row1, int col1, int row2, int col2){
int temp = data[row1][col1];
data[row1][col1] = data[row2][col2];
data[row2][col2] = temp;
}
public State copyState() { //**simpler version of
int i = 0;
int[][] temp = new int[data.length][];
for (int[] row : data) {
temp[i++] = Arrays.copyOf(row, row.length); //**simpler way to copy array
}
return new State(temp);
}
public State(int[][] data) {
super();
this.data = data;
}
}
class Node {
private State state;
private Node parent;
private ArrayList<Node> children;
public Node(State state){
this.state = state;
parent = null;
children = new ArrayList<>();
}
public State getState() { return state; }
public void setState(State state) { this.state = state; }
public Node getParent() { return parent;}
public void setParent(Node parent) { this.parent = parent; }
public ArrayList<Node> getChildren() { return children; }
public void addChild(Node node){
node.setParent(this);
children.add(node);
}
public List<Node> returnSuccessor(){
List<Node> result = new ArrayList<>();
int[][] matrix = getState().getData();
int row = matrix.length;
int col = matrix[0].length;
for(int i=0; i<row; i++){
for(int j=0; j<col; j++){
/* need to check possible move for ALL nodes
* if ( matrix[i][j] == 0) {
rowX = i;
colX = j;
}*/
if( (j-1) >= 0 ){
State temp = getState().copyState();
temp.swap(i, j, i, j-1);
Node left = new Node(temp);
result.add(left);
}
if ( (j+1) < col ){
State temp = getState().copyState();
temp.swap(i, j, i, j+1);
Node right = new Node(temp);
result.add(right);
}
if ( (i-1) >= 0 ){
State temp = getState().copyState();
temp.swap(i, j, i-1, j);
Node top = new Node(temp);
result.add(top);
}
if ( (i+1) < row ){
State temp = getState().copyState();
temp.swap(i, j, i+1, j);
Node down = new Node(temp);
result.add(down);
}
}
}
return result;
}
//override toString rather than creating
@Override
public String toString(){
return Arrays.deepToString(getState().getData());
}
//**override equals rather than creating your own equal
@Override
public boolean equals(Object node){
if (node == this) { return true; }
if (node == null) { return false;}
if (!(node instanceof Node)) {return false; }
return Arrays.deepEquals(getState().getData(), ((Node)node).getState().getData());
}
//** override hashCode so each Node has a unique one
@Override
public int hashCode() {
return toString().hashCode();
}
}
我也認為術語有點令人困惑。 我認為如果每個數據元素都代表一個Node就會被清除,所以int[][] initialState = { {2,1}, {3,0} };
代表4個節點。 這些節點的集合創建了一個樹,它代表一個唯一的狀態。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.