方法有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;
}
}