添加路障-蓝桥杯-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;
    }
}
相关推荐
元亓亓亓2 天前
LeetCode热题100--105. 从前序与中序遍历序列构造二叉树--中等
算法·leetcode·职场和发展
测试老哥2 天前
Selenium 使用指南
自动化测试·软件测试·python·selenium·测试工具·职场和发展·测试用例
仙俊红2 天前
LeetCode每日一题,20250914
算法·leetcode·职场和发展
前端小超超2 天前
capacitor配置ios应用图标不同尺寸
ios·蓝桥杯·cocoa
睡不醒的kun2 天前
leetcode算法刷题的第三十四天
数据结构·c++·算法·leetcode·职场和发展·贪心算法·动态规划
吃着火锅x唱着歌3 天前
LeetCode 1446.连续字符
算法·leetcode·职场和发展
武子康3 天前
AI-调查研究-76-具身智能 当机器人走进生活:具身智能对就业与社会结构的深远影响
人工智能·程序人生·ai·职场和发展·机器人·生活·具身智能
Nan_Shu_6143 天前
Web前端面试题(1)
前端·面试·职场和发展
YuTaoShao3 天前
【LeetCode 每日一题】3000. 对角线最长的矩形的面积
算法·leetcode·职场和发展
007php0073 天前
Redis高级面试题解析:深入理解Redis的工作原理与优化策略
java·开发语言·redis·nginx·缓存·面试·职场和发展