广度优先搜索BFS的一个应用实例(华为编程大赛赛题)

题目:下面是华为编程大赛中的一道题目

 

解法(JAVA):

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

public class MiGong2 {
	public static void main(String[] args) {
		Scanner input = new Scanner(System.in);
		while(input.hasNext()) {
			int row = Integer.parseInt(input.nextLine());
			int col = Integer.parseInt(input.nextLine());
			Node start = null , end = null;
			int[][] arr = new int[row][col];
			//设法将字符串形式  转化成 0-1的矩阵,0表示可以通过,1表示不能通过
			for(int i = 0 ; i < row ; i++) {
				String st = input.nextLine();
				for(int  j = 0 ; j < col ; j++) {
					if(st.charAt(j) == 'B') {
						start = new Node(i,j,0);
						arr[i][j] = 0;
					}else if(st.charAt(j) == 'H') {
						end = new Node(i,j,0);
						arr[i][j] = 0;
					}else if(st.charAt(j) == '#') {
						arr[i][j] = 1;
					}else {
						arr[i][j] = 0;
					}
				}//第一个for
			}//第二个for
			//输出是否有路径
			System.out.println(new MiGong2().isRold(arr,row ,col,start,end));
		}
		input.close();
	}
	
	public String isRold(int[][] arr , int row , int col , Node start , Node end ) {
		String f = "N";
		//定义  上下左右 四个方向
		int[][] direction = {{0,1},{0,-1},{1,0},{-1,0}};
		//创建队列
		LinkedList<Node> queue = new LinkedList<Node>();
		//将开始节点加入队列中去,并设置标记
		queue.offer(start);
		arr[start.x][start.y] = 1;
		//while循环依次遍历节点
		int newX , newY;
		ok:
		while(!queue.isEmpty()) {
			Node temp = queue.poll();
			for(int  i = 0 ; i < 4 ; i++) {
				newX = temp.x + direction[i][0];
				newY = temp.y + direction[i][1];
				//判断  newX和newY越界
				if(newX < 0 || newX >= row || newY < 0 || newY >= col) {
					continue;
				}
				//判断newX和newY是否可以通过
				if(arr[newX][newY] == 1) {
					continue;
				}
				
				//判断newX和newY是否是结束节点
				if(newX == end.x && newY == end.y) {
					f = "Y";
					break ok;
				}
				//构建新的节点
				Node next = new Node(newX,newY,temp.dis+1);
				queue.offer(next);
				arr[newX][newY] = 1;	
			}//for
		}//while
		
		return f;
		
	}
	
}

class Node{
	int x;
	int y;
	int dis;
	public Node(int x , int y , int dis) {
		this.x = x;
		this.y = y;
		this.dis =dis;
	}
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值