LeetCode刷题-网格路径问题-turn

package ENP.Gird;

import java.util.Scanner;
/*
网格转向有消耗的路径问题
6 6
SBBBBB
BXXXXB
BBXBBB
XBBXBB
BXBBXB
BBXBEB
输入描述:起点S; 终点E, 每次上下左右一步,X无法通过,B可通过,转向需要消耗1
*/


//
public class Gird_turn_DFS {
    public static int minTime = Integer.MAX_VALUE;
    public static int beginI = 0;
    public static int beginJ = 0;

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int M = scanner.nextInt();
        int N = scanner.nextInt();
        String[][] matrix = new String[M][N];
        for(int i = 0; i < M; i++){
            String str = scanner.next();
            for(int j = 0; j < N; j++){
                matrix[i][j] = String.valueOf(str.charAt(j));
                if(matrix[i][j].equals("S")){
                    beginI = i;
                    beginJ = j;
                }
            }
        }
        int res = solve(matrix);
        if(res == 0){
            System.out.println(-1);
        }else{
            System.out.println(res);
        }

    }

    public static int solve (String[][] matrix) {
        if(matrix == null) return 0;
        int row = matrix.length;
        int column = matrix[0].length;
        dfs(matrix, beginI, beginJ, row, column, 0, 0);
        return minTime;
    }

    public static void dfs(String[][] matrix, int i, int j, int row, int column, int time, int flag){
        if(matrix[i][j].equals("E")){
            minTime = Math.min(minTime, time);
            return;
        }
        String str = matrix[i][j];

        if(j - 1 >= 0 && (matrix[i][j - 1].equals("B") || matrix[i][j - 1].equals("E"))){
            matrix[i][j] = "X";
            if(flag != 0 && flag != 1) time++;
            dfs(matrix, i, j - 1, row, column, ++time, 1);
            matrix[i][j] = str;
            if(flag != 0 && flag != 1) time--;
            time--;
        }
        if(j + 1 < column && (matrix[i][j + 1].equals("B") || matrix[i][j + 1].equals("E"))){
            matrix[i][j] = "X";
            if(flag != 0 && flag != 2) time++;
            dfs(matrix, i, j + 1, row, column, ++time, 2);
            matrix[i][j] = str;
            if(flag != 0 && flag != 1) time--;
            time--;
        }
        if(i - 1 >= 0 && (matrix[i - 1][j].equals("B") || matrix[i - 1][j].equals("E"))){
            matrix[i][j] = "X";
            if(flag != 0 && flag != 3) time++;
            dfs(matrix, i - 1, j, row, column, ++time,3);
            matrix[i][j] = str;
            if(flag != 0 && flag != 1) time--;
            time--;
        }

        if(i + 1 < row && (matrix[i + 1][j].equals("B") || matrix[i + 1][j].equals("E"))){
            matrix[i][j] = "X";
            if(flag != 0 && flag != 4) time++;
            dfs(matrix, i + 1, j, row, column, ++time,4);
            matrix[i][j] = str;
            if(flag != 0 && flag != 1) time--;
            time--;
        }
    }
}

你可能感兴趣的:(java,leetcode,java,算法)