蓝桥杯刷题之dfs

蓝桥杯刷题之dfs_第1张图片

public class BRTdfs2 {
    public static char[][] map = new char[5][5];
    public static int min = 999999;
    public static int[][] ArrNum = new int[5][5];
    public static void dfs(int i,int j,int step){
        if (map[i][j] == 'B') {
            min = Math.min(step,min);
            return;
        }
        if(map[i][j] == 'A'){
            dfs(i+1,j,step+1);
            dfs(i,j+1,step+1);
        }
        if(map[i][j] == '+'){
            if(j+1 < 5 && ((map[i][j+1] == '-' && ArrNum[i][j+1] == 0) || (map[i][j+1] == 'B'))){
                ArrNum[i][j+1] = 1;
                dfs(i,j+1,step+1);
                ArrNum[i][j+1] = 0;
            }
            if(i+1 < 5 && ((map[i+1][j] == '-' && ArrNum[i+1][j] == 0) || (map[i+1][j] == 'B'))){
                ArrNum[i+1][j] = 1;
                dfs(i+1,j,step+1);
                ArrNum[i+1][j] = 0;
            }
            if (i >= 1 && ((map[i-1][j] == '-' && ArrNum[i-1][j] == 0) || (map[i-1][j] == 'B'))){
                ArrNum[i-1][j] = 1;
                dfs(i-1,j,step+1);
                ArrNum[i-1][j] = 0;
            }
            if(j >= 1 && ((map[i][j-1] == '-' && ArrNum[i][j-1] == 0) || (map[i][j-1] == 'B'))){
                ArrNum[i][j-1] = 1;
                dfs(i,j-1,step+1);
                ArrNum[i][j-1] = 0;
            }
        }else if(map[i][j] == '-'){
            if(j+1 < 5 && ((map[i][j+1] == '+' && ArrNum[i][j+1] == 0) || (map[i][j+1] == 'B'))){
                ArrNum[i][j+1] = 1;
                dfs(i,j+1,step+1);
                ArrNum[i][j+1] = 0;
            }
            if(i+1 < 5 && ((map[i+1][j] == '+' && ArrNum[i+1][j] == 0) || (map[i+1][j] == 'B'))){
                ArrNum[i+1][j] = 1;
                dfs(i+1,j,step+1);
                ArrNum[i+1][j] = 0;
            }
            if (i >= 1 && ((map[i-1][j] == '+' && ArrNum[i-1][j] == 0) || (map[i-1][j] == 'B'))){
                ArrNum[i-1][j] = 1;
                dfs(i-1,j,step+1);
                ArrNum[i-1][j] = 0;
            }
            if(j >= 1 && ((map[i][j-1] == '+' && ArrNum[i][j-1] == 0) || (map[i][j-1] == 'B'))){
                ArrNum[i][j - 1] = 1;
                dfs(i, j - 1, step + 1);
                ArrNum[i][j - 1] = 0;
            }
        }
        return;
    }
    public static void main(String[] args){
        map = new char[][]{{'A', '+', '-', '+', '-'},
                {'-','+','-','-','+'},
                {'-','+','+','+','-'},
                {'+','-','+','-','+'},
                {'B','+','-','+','-'}};
        ArrNum[0][0] = 1;
        dfs(0,0,0);
        System.out.println(min);
    }
}

学了一点dfs,完全自己想的代码哈哈哈哈哈

 

你可能感兴趣的:(深度优先,蓝桥杯,算法)