蓝桥杯国赛—路径之谜(dfs详细解法)

一.题目

二.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"};//下,左,右,上
}

三.测试结果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值