迷宫问题

方法有dfs、bfs,在这里介绍bfs,因为这类问题可能会涉及到求解最短路径的情况。
一、分析
针对蓝桥杯的某一年真题来分析(竞码上的7053题):迷宫
大体上,两个核心:
1.通过队列找出最短的路径,并在每个地方标注U、D、L、R四个方向。
2.通过ArrayList回溯,将最终结果输出。

二、代码实现

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

public class T7053 {
	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		int n = in.nextInt();
		int m = in.nextInt();
		char[][] maze = new char[n][m];
		for (int i = 0; i < maze.length; i++) {
			maze[i] = in.next().toCharArray();
		}
		bfs(maze);
	}

	private static void bfs(char[][] maze) {
		boolean tag=false;
		int row=maze.length;
		int col=maze[0].length;
		int[][] vis=new int[row][col];
		char[][] dir=new char[row][col];
		int[] dir_x= {1,0,0,-1};//D L R U
		int[] dir_y= {0,-1,1,0};
		
		Queue<Point> queue=new LinkedList<Point>();
		queue.add(new Point(0, 0, 0));
		vis[0][0]=1;
		while(!queue.isEmpty()) {
			Point point=queue.poll();
			if (point.getX()==row-1 && point.getY()==col-1) {
				tag=true;
				break;
			}
			for (int i = 0; i < dir_x.length; i++) {
				int temp_x=point.getX()+dir_x[i];
				int temp_y=point.getY()+dir_y[i];
				if (temp_x>=0 && temp_x<row && temp_y>=0 && temp_y<col && vis[temp_x][temp_y]==0 && maze[temp_x][temp_y]=='0') {
					queue.add(new Point(temp_x, temp_y, point.getStep()+1));
					vis[temp_x][temp_y]=1;	
					if (i==0) {
						dir[temp_x][temp_y]='D';
					}else if (i==1) {
						dir[temp_x][temp_y]='L';
					}else if (i==2) {
						dir[temp_x][temp_y]='R';
					}else if (i==3) {
						dir[temp_x][temp_y]='U';
					}
				}
			}
		}
		
//		回溯
		ArrayList<Character> recall=new ArrayList<Character>();
		int i=row-1;
		int j=col-1;
		while(!(i==0 && j==0)) {
			recall.add(dir[i][j]);
			if (dir[i][j]=='D') {
				i-=1;
			}else if (dir[i][j]=='L') {
				j+=1;
			}else if (dir[i][j]=='R') {
				j-=1;
			}else if (dir[i][j]=='U') {
				i+=1;
			}
		}
		for (int k = recall.size()-1; k>=0; k--) {
			System.out.print(recall.get(k));
		}
	}
}

class Point {
	private int x;
	private int y;
	private int step;

	public Point(int x, int y, int step) {
		super();
		this.x = x;
		this.y = y;
		this.step = step;
	}

	public int getX() {
		return x;
	}

	public void setX(int x) {
		this.x = x;
	}

	public int getY() {
		return y;
	}

	public void setY(int y) {
		this.y = y;
	}

	public int getStep() {
		return step;
	}

	public void setStep(int step) {
		this.step = step;
	}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值