一.题目
二.dfs解法
使用dfs算法可以递归遍历所有可能路径,如果找到错误的路径就进行回溯,只有找到正确的路径才会输出
public class Main {
static class pair{
int x;
int y;
public pair(int x,int y)
{
this.x = x;
this.y = y;
}
}
public static void bfs()
{
Queue<pair> queue = new LinkedList<>();
queue.add(new pair(0, 0));//添加元素
mark[0][0] = "";//赋空
while(!queue.isEmpty())//如果队列不为空
{
pair top = queue.poll();//队头元素出队
for(int i = 0;i<4;i++)//遍历上下左右四个方向
{
int nex = top.x+dx[i];
int ney = top.y+dy[i];
if(nex >= 0 && nex < n && ney >= 0 && ney<m && mark[nex][ney].equals("") && map[nex][ney]=='0')
{
mark[nex][ney] = mark[top.x][top.y] + str[i];
queue.add(new pair(nex,ney));
}
}
}
System.out.println(mark[n-1][m-1]);
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
n = 30;
m = 50;
//String s = scanner.nextLine();
for(int i = 0;i<n;i++)
map[i] = scanner.nextLine().toCharArray();
for (int i = 0; i < n; i++) {
for(int j = 0;j<m;j++){
mark[i][j] = "";
}
}
bfs();
}
public static final int N = 100;
public static int n,m;//地图的行列
public static char[][] map = new char[N][N];//地图
public static String[][] mark = new String[N][N];//如果mark[i][j]为null那就没有走过该点,还可以存储信息
public static int[] dx = {1,0,0,-1};
public static int[] dy = {0,-1,1,0};
public static String[] str = {"D","L","R","U"};//下,左,右,上
}
三.测试结果