廣度優先搜索 迷宮 問題 java實現

題目如下 : 

    

本題採用廣度優先搜索解決,廣度優先搜索相對於深度優先搜索我覺得較爲容易理解,因爲不用遞歸和回溯,用循環就可以解決,廣度優先搜索的有點在於掃描搜索樹的順序是從根節點往下一層一層的搜索,搜索在求解最優解的時候比深度有優勢,因爲深度要求最優解的話需要遍歷所有結果才能得出,但是廣度優先搜索掃描到的第一個結果就是最優結果,具體的代碼如下:

   

import java.util.*;
class Point{int x,y,step;public Point(int x,int y,int step){this.x=x;this.y=y;this.step=step;}}public class BFSMigong1 { static char[][] datas = null; static int[][] visit = null; static int[][] oprate = {{0,1},{1,0},{0,-1},{-1,0}}; static int result = -1;public static void main(String[] args) {// TODO Auto-generated method stub Scanner sc = new Scanner(System.in); int n=sc.nextInt(); int m=sc.nextInt(); datas = new char[n+2][m+2]; visit = new int[n+2][m+2]; int startX=0,startY=0; String temp = null; for(int i=1;i<=n;i++){ temp = sc.next(); for(int j=1;j<=m;j++){ datas[i][j] = temp.charAt(j-1); if(datas[i][j] == 'S'){ startX=i; startY=j; } } } bfs(startX,startY); System.out.print(result);}public static void bfs(int x,int y){Queue<Point> queue = new LinkedList<Point>();Point p = new Point(x,y,0); //插入根節點queue.offer(p);Point temp = null;
                visit[x][y]=1;	
                boolean isFind = false;
		while(!queue.isEmpty()){
			temp = queue.poll(); //從開頭彈出一個節點
			for(int i=0;i<4;i++){  //遍歷這個節點對應的位置能夠到達的位置
				if(visit[temp.x+oprate[i][0]][temp.y+oprate[i][1]]==0&&datas[temp.x+oprate[i][0]][temp.y+oprate[i][1]]!='#'&&datas[temp.x+oprate[i][0]][temp.y+oprate[i][1]]!='\0'){
					visit[temp.x+oprate[i][0]][temp.y+oprate[i][1]]=1;
					if(datas[temp.x+oprate[i][0]][temp.y+oprate[i][1]]=='T'){//因爲在這個題目中初始位置不可能是目標位置,所以在這裏判斷能夠少走一層
						result = temp.step+1;  //在下一層到達,所以結果要這一個位置的步數+1
						isFind = true;
						break;
					}else{
						queue.offer(new Point(temp.x+oprate[i][0],temp.y+oprate[i][1],temp.step+1));
					}
				}
			}
			if(isFind){
				break ;
			}
		}
	}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章