AcWing
  • 首页
  • 题库
  • 题解
  • 分享
  • 问答
  • 活动
  • 应用
  • 吐槽
  • 登录/注册

AcWing 1113. 红与黑 JAVA    原题链接    简单

作者: 作者的头像   天乔巴夏丶 ,  2021-01-14 00:30:10 ,  阅读 15


0



import java.io.*;


public class Main {

    static int n = 25, row, col,cnt;
    static int[] dx = {-1, 0, 1, 0}, dy = {0, 1, 0, -1};
    static char[][] g = new char[n][n];

    public static void main(String[] args) throws Exception {

        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

        while (true) { // 多组测试用例
            cnt = 0; // 每个用例都初始化一下 0
            String[] ss = reader.readLine().split(" ");
            row = Integer.parseInt(ss[1]);
            col = Integer.parseInt(ss[0]);
            // 读到0 0 结束
            if (row == 0 || col == 0) break;
            int x = 0, y = 0;

            for (int i = 0; i < row; i++) {
                String s = reader.readLine();
                for (int j = 0; j < col; j++) {
                    g[i][j] = s.charAt(j);
                    if (g[i][j] == '@') { // 记录一下初始化的x y的位置
                        x = i;
                        y = j;
                    }
                }
            }
            dfs(x, y); // 开始dfs
            System.out.println(cnt);
        }
    }

    static void dfs(int x, int y) {
        g[x][y] = '#'; // 标记一下 走过了
        cnt++;
        for (int i = 0; i < 4; i++) {
            int a = x + dx[i];
            int b = y + dy[i];
            // 不越界 且 为黑 才继续走
            if (a >= 0 && a < row && b >= 0 && b < col && g[a][b] == '.') {
                dfs(a, b);
            }
        }
    }
}

0 评论

你确定删除吗?

© 2018-2020 AcWing 版权所有  |  京ICP备17053197号-1
联系我们  |  常见问题
AcWing
请输入登录信息
更多登录方式: 微信图标 qq图标
请输入绑定的邮箱地址
请输入注册信息