本文主要是介绍java实现从迷宫寻找出路算法(广度优先搜索),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
import com.alibaba.fastjson.JSONObject;
import java.util.ArrayDeque;
/**
* Created by Administrator on 2017/7/12.
*/
public class ScopeSearchFirst {
public static void main(String... args) {
int[][] a = new int[51][51];//初始化为0
System.out.println(JSONObject.toJSONString(a));
int[][] book = new int[51][51];//初始化为0
int[][] next = {{0,1},{0,-1},{1,0},{-1,0}};
for(int i=0;i<=50;i++) {
for (int j = 0; j < 50; j++) {
if (i == 0 && j == 0) {
continue;
}
if (j == i) {
a[i][j] = 1;//设置为障碍物
break;
}
}
}
System.out.println("初始化后的结果:");
for(int i=0;i<50;i++)
for(int j=0;j<50;j++)
if(j==49)
System.out.println();
else
System.out.print(a[i][j]);
int startx = 0;
int starty = 0;
int p = 35;
int q = 23;
ArrayDequequeue = new ArrayDeque();
Note note = new Note();
note.setX(startx);
note.setY(starty);
note.setS(0);
queue.addLast(note);
book[0][0]=1;
int flag = 0;
int tx=0;
int ty=0;
while (!queue.isEmpty()) {
for (int k = 0; k <= 3; k++) {
tx = queue.getFirst().getX()+next[k][0];
ty = queue.getFirst().getY()+next[k][1];
if(tx<0||tx>=50||ty<0||ty>=50)
continue;
if(a[tx][ty]==0&&book[tx][ty]==0){
book[tx][ty]=1;
Note newNote = new Note();
newNote.setX(tx);
newNote.setY(ty);
newNote.setF(queue.getFirst());
newNote.setS(queue.getFirst().getS()+1);
queue.addLast(newNote);
}
if(tx==p&&ty==q){
flag=1;
break;
}
}
if(flag==1)
break;
queue.removeFirst();
}
System.out.println("最短距离:"+queue.getLast().getS());
}
static class Note{
private int x;
private int y;
private int s;
private Note f;
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public int getS() {
return s;
}
public void setS(int s) {
this.s = s;
}
public Note getF() {
return f;
}
public void setF(Note f) {
this.f = f;
}
}
}
这篇关于java实现从迷宫寻找出路算法(广度优先搜索)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!