添加路障-蓝桥杯-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;
    }
}
相关推荐
dayuOK630716 天前
写作卡壳怎么办?我的“5分钟启动法”
人工智能·职场和发展·自动化·新媒体运营·媒体
枫子有风16 天前
LLM-Agent智能体(大厂面试常问)
面试·职场和发展·llm·agent
重生之后端学习16 天前
Java入门
java·开发语言·职场和发展
AIHR数智引擎16 天前
KPI物理失效:AI原生组织的效能重构与技能度量
人工智能·经验分享·职场和发展·重构·ai-native·aihr
想吃火锅100516 天前
【leetcode】121.买卖股票的最佳时机js/c++
算法·leetcode·职场和发展
程序员小远16 天前
自动化测试基础知识总结
自动化测试·软件测试·python·selenium·测试工具·职场和发展·测试用例
嘿黑嘿呦16 天前
chap 8排序
算法·蓝桥杯·排序算法·软件工程
珊瑚里的鱼16 天前
【递归】汉诺塔
算法·深度优先
小欣加油16 天前
leetcode3612 用特殊操作处理字符串I
数据结构·c++·算法·leetcode·职场和发展
旧曲重听116 天前
2026前端技术从「夯」到「拉」
前端·程序人生·职场和发展·软件工程