這篇文章給大家分享的是有關(guān)怎么樣使用java算法BFS來求迷宮出口短路徑的內(nèi)容。小編覺得挺實用的,因此分享給大家做個參考。一起跟隨小編過來看看吧。
隊列的建立
static Queue r = new LinkedList(); //創(chuàng)建隊列
隊列的基本方法
r.offer(); 入隊尾
r.poll(); 出隊首
r.peek(); 隊首的內(nèi)容
代碼實現(xiàn):
全局變量設(shè)置
package Two; import java.util.LinkedList; import java.util.Queue; import java.util.Scanner; public class BFS { static int a[][] = new int [100][100]; //輸入迷宮 static int v[][] = new int [100][100]; //走過的標記為1 static int startx,starty; //輸入起點位置 static int p,q; //輸入要到達的坐標位置 static int dx[] = {0,1,0,-1}; //方向數(shù)組 static int dy[] = {1,0,-1,0}; static Queue<point> r = new LinkedList<point>(); //創(chuàng)建隊列 static class point{ //建立類坐標屬性 int x; int y; int step; }
輸入迷宮和起始位置,目標位置
public static void main(String[] args) { Scanner in = new Scanner(System.in); int m = in.nextInt(); int n = in .nextInt(); for(int i=1;i<=m;i++) //輸入迷宮 for(int j=1;j<=n;j++) a[i][j] = in.nextInt(); startx = in.nextInt(); starty = in.nextInt(); //輸入目標和起始位置 p = in.nextInt(); q = in.nextInt();
BFS算法開始
1、設(shè)置隊首
//BFS point start = new point(); //定義一個初始類作為隊首 start.x = startx; start.y = starty; start.step = 0; r.offer(start); v[startx][starty]=1;
2、進入循環(huán)體
while(!r.isEmpty()) { //當隊列為空時跳出循環(huán) int x = r.peek().x; //把隊首的屬性賦值 int y = r.peek().y; int step = r.peek().step; if(x==p && y==q) { //到達目的地,退出循環(huán) System.out.println(step); break; } for(int i=0;i<4;i++) { //廣度遍歷,右下左上分別入隊 int tx= x+dx[i]; int ty= y+dy[i]; if(a[tx][ty] == 1 && v[tx][ty]==0) { //判斷是否可以入隊 //入隊 point temp = new point(); //建立一個臨時類 temp.x = tx; temp.y = ty; temp.step = r.peek().step +1; r.offer(temp); //入隊 v[tx][ty]=1; //標記為1 } } r.poll(); //拓展完了需要隊首出隊 } } }
感謝各位的閱讀!關(guān)于怎么樣使用java算法BFS來求迷宮出口短路徑就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,讓大家可以學(xué)到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!
本文名稱:怎么樣使用java算法BFS來求迷宮出口短路徑-創(chuàng)新互聯(lián)
網(wǎng)站鏈接:http://chinadenli.net/article44/deioee.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供App開發(fā)、用戶體驗、靜態(tài)網(wǎng)站、電子商務(wù)、做網(wǎng)站、商城網(wǎng)站
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容