添加路障-蓝桥杯-DFS

自己另辟蹊径想的新思路 果然好像还是不太行呀

java 复制代码
import java.util.Scanner;

public class Main {
    static int T;//样例组数
    static int n;//矩阵大小
    static int[] X = {0,1,0,-1};
    static int[] Y = {1,0,-1,0};
    static int[] X1 = {1,0,-1,0};
    static int[] Y1 = {0,-1,0,1};
    static int flag = 0;
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        T = scan.nextInt();
        while((T--)>0)
        {
            n = scan.nextInt();
            char[][] arr = new char[n][n];
            int[][] vis = new int[n][n];
            for(int i = 0;i<n;i++)
            {
                arr[i] =scan.next().toCharArray();
            }
            if(!dfs(0,0,vis,arr,n))//第一次就不通
            {
                System.out.println(0);
            }
            else
            {
                dfs1(0,0,vis,arr,n);//第二次标记
                int[][] vis1 = new int[n][n];
                if(dfs(0,0,vis1,arr,n))
                {
                    System.out.println(2);
                }
                else
                {
                    System.out.println(1);
                }
            }
        }
    }
    static boolean dfs(int x,int y,int[][] vis,char[][] arr,int n)
    {
        if(arr[x][y] == 'C') return true;
        if(arr[x][y]!='A') vis[x][y] = 1;
        for(int i = 0;i<4;i++)
        {
            int x1 = x + X[i];
            int y1 = y + Y[i];
            if(x1>=0&&x1<n&&y1>=0&&y1<n&&vis[x1][y1]==0&&arr[x1][y1]!='X')
            {
                if(dfs(x1,y1,vis,arr,n)) return true;
            }
        }
        return false;
    }
    static boolean dfs1(int x,int y,int[][] vis,char[][] arr,int n)
    {
        if(arr[x][y] == 'C' ) return true;
        if(arr[x][y]!='A') vis[x][y] = 2;
        for(int i = 0;i<4;i++)
        {
            int x1 = x + X1[i];
            int y1 = y + Y1[i];

            if(x1>=0&&x1<n&&y1>=0&&y1<n&&vis[x1][y1]==1&&arr[x1][y1]!='X')
            {
                arr[x1][y1] = 'X';
                return true;
            }

            if(x1>=0&&x1<n&&y1>=0&&y1<n&&vis[x1][y1]!=2&&arr[x1][y1]!='X')
            {
                if(dfs1(x1,y1,vis,arr,n)) return true;
            }
        }
        return false;
    }
}
相关推荐
eggrall11 小时前
Leetcode 最大连续 1 的个数 III(medium)
算法·leetcode·职场和发展
米粒111 小时前
力扣算法刷题Day 49(接雨水)
算法·leetcode·职场和发展
_深海凉_12 小时前
LeetCode热题100-前 K 个高频元素
算法·leetcode·职场和发展
始三角龙12 小时前
LeetCode hoot 100 -- 和为K的子数组
算法·leetcode·职场和发展
算法即正义12 小时前
国家安全知识竞赛题库精讲与备赛指南
职场和发展·学习方法
_深海凉_12 小时前
LeetCode热题100-最长递增子序列
算法·leetcode·职场和发展
星马梦缘12 小时前
离散数学——图论 作战记录
算法·深度优先·图论·离散数学·生成树·哈密顿图·欧拉图
测试19981 天前
2026最新软件测试面试八股文【附文档】
自动化测试·软件测试·python·测试工具·面试·职场和发展·测试用例
故事和你911 天前
洛谷-数据结构1-4-图的基本应用1
开发语言·数据结构·算法·深度优先·动态规划·图论
小欣加油1 天前
leetcode2078 两栋颜色不同且距离最远的房子
数据结构·c++·算法·leetcode·职场和发展