牛客網編程題-逛公園-Java-BFS算法

又是晴朗的一天,牛牛的小夥伴們都跑來找牛牛去公園玩。但是牛牛想呆在家裏看E3展,不想出去逛公園,可是牛牛又不想鴿掉他的小夥伴們,於是找來了公園的地圖,發現公園是由一個邊長爲n的正方形構成的,公園一共有m個入口,但出口只有一個。公園內有一些湖和建築,牛牛和他的小夥伴們肯定不能從他們中間穿過,所以只能繞行。牛牛想知道他需要走的最短距離並輸出這個最短距離。

輸入描述:

第一行輸入一個數字n(1≤n≤1000)表示公園的邊長
接下來會給你一個n*n的公園地圖,其中 . 表示公園裏的道路,@表示公園的入口,*表示公園的出口,#表示公園內的湖和建築。
牛牛和他的小夥伴們每次只能上下左右移動一格位置。
輸入保證公園入口個數m(1≤m≤10000)且所有的入口都能和出口相連。

輸出描述:

輸出牛牛需要行走的最短距離。

示例1

輸入

10
.@....##@.
......#...
...@..#...
###.......
....##..#.
...####...
@...##....
#####.....
..##*####.
#.........

輸出

16

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


public class Main3 {
	public static void main(String[] args){
		 Scanner sc = new Scanner(System.in); 
		 int n = sc.nextInt();
		 sc.nextLine();
		 char arr [][] = new char[n][n];
		 char a[] = new char[n];

		 int p = 0,q = 0;
		 for(int i=0;i<n;i++){
			 String str = sc.nextLine();
			 a = str.toCharArray();
			 for(int j=0;j<n;j++){
				 arr[i][j] = a[j];  
				 if(a[j]=='*'){
					p = i;
					q = j;
				 }
			 }			 
		 }
		 int number = bfs(arr,p,q,n);
		 System.out.println(number);
	}

	private static int bfs(char[][] arr, int p, int q, int n) {
				
		int deep[][] = new int[n][n];
		for (int k = 0; k < n; k++)
	        for (int l = 0; l < n; l++)
	            deep[k][l] = -1;
		deep[p][q] = 0;
		Queue<Point> queue = new LinkedList<Point>();
		queue.offer(new Point(p, q));
		int[] tx = { -1, 1, 0, 0 };
	    int[] ty = { 0, 0, 1, -1 };
		while(queue.size()>0){
			Point top = queue.poll();
			int i = top.x;
			int j = top.y;
			if(arr[i][j]=='@'){
				return deep[i][j];
			}
			for (int k = 0; k < 4; k++) {
	            int x = top.x + tx[k];
	            int y = top.y + ty[k];	//p爲當前位置;
	            if (x >= 0 && x < n && y >= 0 && y < n && arr[x][y] != '#' && deep[x][y] == -1) {
	                deep[x][y] = deep[top.x][top.y] + 1;
	                queue.offer(new Point(x, y));
	            }
	         } 	         
		}
		return 0;
	}	
}

 

 

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