解救小哈(廣搜代碼)

題目描述:

輸入m,n,表示地圖的大小,地圖用0和1來表示,表示障礙和空地,再輸入小哼的起始點,和小哈的位置

輸出最小的步數

輸入樣例:

5  4

0 0 1 0

0 0 0 0 

0 0 1 0

0 1 0 0

0 0 0 1

0 0 3 2

take notes:廣搜的特點層層遞進,需要用一個隊列來存儲結構體

import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;

public class 解救小哈廣搜 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner in =  new Scanner(System.in);
		Queue<node> qe = new LinkedList<node>();
		int[][] mp = new int[55][55];
		int[][] book = new int[55][55];
		int[][] next = {{0,1},{1,0},{0,-1},{-1,0}};
		int m=in.nextInt();
		int n=in.nextInt();
		int tx,ty;
		for(int i=0;i<m;i++){
			for(int j=0;j<n;j++){
				mp[i][j] = in.nextInt();
			}
		}
		int startx=in.nextInt();
		int starty=in.nextInt();
		int p=in.nextInt();
		int q=in.nextInt();
		int step=0;
		node no = new node(startx, starty,step);
		qe.add(no);
		book[startx][starty]=1;
		main:while(qe.size()!=0){
			for(int i=0;i<=3;i++){
				tx=qe.peek().x+next[i][0];
				ty=qe.peek().y+next[i][1];
				if(tx<0||tx>=m||ty<0||ty>=n)continue;
				if(mp[tx][ty]==0&&book[tx][ty]==0){
					book[tx][ty]=1;
					qe.add(new node(tx,ty,qe.peek().s+1));
					step=qe.peek().s;
				}
				
				if(tx==p&&ty==q){System.out.println(step+1);
					break main;
				}
				
			}
			step++;
			qe.poll();
		}
		
	}

}
class node{
	int x;
	int y;
	int s;
	node(int x,int y,int s){
		this.x=x;
		this.y=y;
		this.s=s;
	}
}

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