java三角形寻路_Java版的广度优先寻路(BFS+并查集思想)

importjava.util.Deque;importjava.util.LinkedList;classnode{intx;inty;

}classSolution{private int dir[][]=new int[][] {{0,-1},{-1,0},{0,1},{1,0}};privatenode parentx[][];private intCount[][];private booleanused[][];private node start=newnode();private node end=newnode();private Deque queue=new LinkedList();privatenode temp;private boolean flag=false;public booleanisCheckMove(String[] map,node start) {return start.x>=0&&start.x=0&&start.y

}public booleanprintPath(String[] map) {while(parentx[temp.x][temp.y].x!=temp.x||parentx[temp.x][temp.y].y!=temp.y) {

System.out.print(map[temp.x].charAt(temp.y)+"->");

temp=parentx[temp.x][temp.y];

}

System.out.println(map[temp.x].charAt(temp.y));return true;

}public intdfs(String[] map,node start) {

queue.offer(start);

used[start.x][start.y]=true;

Count[start.x][start.y]=1;while(!queue.isEmpty()) {

start=queue.pop();for(int i=0;i<4;++i) {

temp=newnode();

temp.x=start.x+dir[i][0];

temp.y=start.y+dir[i][1];if(temp.x==end.x&&temp.y==end.y) {

flag=true;

queue.addLast(temp);

parentx[temp.x][temp.y]=start;

Count[temp.x][temp.y]=Count[start.x][start.y]+1;

used[temp.x][temp.y]=true;break;

}if(isCheckMove(map,temp)&&!used[temp.x][temp.y]) {

queue.addLast(temp);

parentx[temp.x][temp.y]=start;

Count[temp.x][temp.y]=Count[start.x][start.y]+1;

used[temp.x][temp.y]=true;

}

}if(flag) {break;

}

}returnCount[temp.x][temp.y];

}public booleannums(String map[]) {

queue.clear();

parentx=new node[map.length][map[0].length()];

Count=new int[map.length][map[0].length()];

used=new boolean[map.length][map[0].length()];for(int i=0;i

used[i][j]=false;

Count[i][j]=0;

node tmp=newnode();

tmp.x=i;

tmp.y=j;

parentx[i][j]=tmp;if(map[i].charAt(j)=='#') {

end.x=i;

end.y=j;

}if(map[i].charAt(j)=='@') {

start.x=i;

start.y=j;

}

}

}

System.out.println(dfs(map,start));

printPath(map);return true;

}

}public classFirst{public static voidmain(String[] args) {

Solution space= newSolution();

String map[]= {"****","@***","&&&&","&&&&","**"};

space.nums(map);for(String str:map) {

System.out.println(str);

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值