题目:下面是华为编程大赛中的一道题目
解法(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;
}
}