救救孩子吧,快疯了
查看原帖
救救孩子吧,快疯了
671246
zhu5001210249楼主2024/3/21 17:43

我不理解,为什么dfs里面他不会把字符0改为*

package com.LQ3yue16;

import java.util.Scanner;

public class P1506 {
    //可以在外面加上一圈0,这个样子在最外面开始搜0,就不会漏掉0,把0变成墙
    static int n;
    static int m;
    static int[] dx = {-1, 0, 1, 0};
    static int[] dy = {0, 1, 0, -1};
    static char[][] ans = new char[505][505];


    public static void dfs(int x,int y) {

        ans[x][y] = '*';

        for(int i=0;i<4;i++) {
            int bx = x + dx[i];
            int by = y + dy[i];
            if(bx>=0 && by>=0 && bx<=n+1 && by<=m+1 && ans[bx][by]=='0') {
                dfs(bx,by);
            }
        }

    }


    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        n = sc.nextInt();
        m = sc.nextInt();
        char[][] res = new char[505][505];
        //输入字符串一定是0开始的
        for (int i = 0; i < n; i++) {
            String s = sc.next();
            for (int j = 0; j < m; j++) {
                char c = s.charAt(j);
                res[i][j] = c;
            }
        }

        //把数组整体下标都往前一位
        for(int i=1;i<=n;i++) {
            for(int j=1;j<=m;j++) {
                ans[i][j] = res[i-1][j-1];
            }
        }

        dfs(0,0);

        int count=0;
        for(int i=1;i<=n;i++) {
            for (int j = 1; j <= m; j++) {

                if(ans[i][j]=='0') {
                    count++;
                }
            }
            System.out.println();
        }

        System.out.println(count);
    }
}

2024/3/21 17:43
加载中...