gpt4 book ai didi

java - 寻找最短路径的递归方法

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:26:08 26 4
gpt4 key购买 nike

<分区>

    ########
#C....G#
##.##C##
#..C..S#
#C.....#
########

S- starting Point
G-Goal
"#"- Blocked Path
"."- Free Paths
"C"- Checkpoints must be visited

Any Points can be visited(S,G,C,".") 可以多次访问。 最后应该以G结尾

我想找到 S 和 G 之间的最短路径。我正在使用 BFS 方法来找到它,但问题是它会生成数千个线程。我的代码适用于 4x4 阵列,但对于 50x50 的大阵列,它会崩溃:

java.lang.OutOfMemoryError: unable to create new native thread

请帮助我改进解决此问题的方法。

public void distancecalculator(char[][] problem ,Point start ,int distancefound, ArrayList<Point> refernce) {

Point p = new Point();
LinkedList<Point> q = new LinkedList<>();
q.add(start);
int []x = {1,-1,0,0};
int []y = {0,0,1,-1};
int[][]dist = new int[m][n];
for(int []a : dist){
Arrays.fill(a,-1);
}
if(distanceend==true)
enddistance = dist;
dist[start.x][start.y] = distancefound;

while(!q.isEmpty()){
// if(distanceend == true)
p = q.removeFirst();
// else
// p = q.getFirst();
// ExecutorService execute = Executors.newFixedThreadPool(200);
for (int i = 0; i < 4; i++) {
int a = p.x + x[i];
int b = p.y + y[i];

if (a >= 0 && b >= 0 && a < m && b < n && dist[a][b] == -1 && problem[a][b] != '#' ) {

dist[a][b] = 1 + dist[p.x][p.y];
if (distanceend==true)
{
enddistance[a][b] = dist[a][b];
q.add(new Point(a,b));
}
if (distanceend==false)
{
// virtual++;
Point neworigin = new Point();
neworigin.x = a;
neworigin.y = b;
refernce.add(neworigin);
char[][] newproblem = new char[m][n];
//newproblem = problem;
int k=0;
for(int s=0 ;s<m;s++)
{
for(int j=0;j<n;j++)
{
newproblem[s][j] = problem[s][j];
if(problem[a][b]=='@')
newproblem[a][b]= '.';
if(newproblem[s][j]=='@')
k=k+1;
}

}
// System.out.println(k)
// System.out.println("1");

System.out.println(neworigin);
if(k>0)
{
ArrayList<Point> sompathak = (ArrayList<Point>)refernce.clone();

solver s = new solver(newproblem , neworigin,dist[a][b] , refernce );

som = new Thread(s);
som.start();

// execute.submit(s);
}

if(k==0)
{ // System.out.println("why god");

if(enddistance[a][b]!=-1)
{

dist[a][b] = dist[a][b] + enddistance[a][b];

temp2 = dist[a][b];
System.out.println("Answer is "+ temp2);

System.exit(1);

}
}
}
}
}
}

distanceend boolean 表达式用于计算从末端到每个点的距离(如果不可能则为 -1)或者我正在解决问题(寻找最短距离)

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com