您的位置:首页 > 编程语言 > Java开发

java实现从迷宫寻找出路算法(广度优先搜索)

2017-07-12 16:23 501 查看
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;

ArrayDeque queue = 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;
}
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: