我有一个深度优先的搜索练习.
这项练习的目标是找到一条从迷宫开始到结束的有效路径.
这是我的代码:
Node.java!Node.java!
public class Node
{
private int position;
private int type;
private boolean IsExit;
public Node(int position,int type,boolean IsExit)
{
this.position = position;
this.type = type;
this.IsExit = IsExit;
}
public int getPosition()
{
return position;
}
public int getType()
{
return type;
}
public boolean getIsExit()
{
return IsExit;
}
public void setIsExit(boolean b)
{
IsExit = b;
}
}
Search算法rithm.java
import java.util.Random;
import java.lang.System;
public class Search算法rithm
{
protected int gridSize;
protected int gridLength;
protected Node[][] grid;
public Search算法rithm(int gridSize)
{
int gridLength = (int) Math.sqrt(gridSize);
this.gridSize = gridSize;
this.gridLength = gridLength;
Node[][]arr = new Node[gridLength][gridLength];
Random r = new Random();
for(int i=0;i<gridSize;i++)
{
Node n;
if(i==0)
{
n= new Node(i,0,false);
arr[i][i] = n;
}
else if(i==gridSize-1)
{
n = new Node(i,0,true);
arr[gridLength-1][gridLength-1] = n;
}
else
{
int x = i%gridLength;
int y = i/gridLength;
n = new Node(i,r.nextInt(2),false);
arr[x][y] = n;
}
}
this.grid = arr;
}
public void print()
{
for(int i=0;i<gridLength;i++)
{
for(int j=0;j<gridLength;j++)
{
System.out.print("Position:"+grid[j][i].getPosition()+" Type:"+grid[j][i].getType()+" ");
}
System.out.println();
}
}
}
grid
是类Node
的二维数组:它有2个坐标x和y.x被Node.position%i
找到,Y被Node.position/i
找到.
DeepFirstSearch.java
import java.lang.System;
public class DeepFirstSearch extends Search算法rithm {
private int[] position;
public DeepFirstSearch(int gridSize) {
super(gridSize);
position = new int[2];
position[0]=0;
position[1]=0;
}
public int calc(int[]position)
{
System.out.println(grid[position[0]][position[1]].getPosition());
if(grid[position[0]][position[1]].getType()==1)
{
System.out.println("Path been blocked!Exit status:"+1);
return 1;
}
else if(grid[position[0]][position[1]].getIsExit())
{
System.out.println("Path been found");
return 0;
}
else
{
if(position[0]<gridLength-1)
{
position[0]++;
calc(position);
}
if(position[0]>0)
{
position[0]--;
calc(position);
}
if(position[1]<gridLength-1)
{
position[1]++;
calc(position);
}
if(position[1]>0)
{
position[1]--;
calc(position);
}
}
return -1;
}
}
int[] position
存储当前Node
的位置.如果我们用Node.getType()==1
命中Node
,则路径无效.Node
和getIsExit()==true
是理想的目的地(在我的示例中它只是1).
#Main.Java#
public class Main {
public static void main(String[] args) {
DeepFirstSearch sch = new DeepFirstSearch(9);
sch.print();
int[]pos = {0,0};
sch.calc(pos);
}
}
我在main
函数中将初始位置设置为{0,0}
.
问题是,当我运行程序时,我得到这样的输出:
Position:0 Type:0 Position:1 Type:0 Position:2 Type:1
Position:3 Type:1 Position:4 Type:1 Position:5 Type:1
Position:6 Type:0 Position:7 Type:1 Position:8 Type:0
0
1
2
Path been blocked!Exit status:1
1
2
Path been blocked!Exit status:1
1
2
Path been blocked!Exit status:1
1
2
Path been blocked!Exit status:1
1
2
...
因此,它继续下go ,直到抛出StackOverflowException
分.为什么该算法一直在访问相同的 node ?