【社区 高校算法学习社区蓝桥刷题帖子详情第十四届蓝桥杯三月真题刷题训练——第 19 天 (3.22) 灌溉 & 小朋友崇拜圈& 括号序列 & 砍竹子】

文章包含两个Java程序,第一个程序使用广度优先搜索(BFS)进行灌溉区域的模拟,计算可灌溉的格子数;第二个程序通过递归方法解决小朋友崇拜圈的问题,找出最长的崇拜链。
摘要由CSDN通过智能技术生成

第一题:灌溉

import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;

public class Main {

    
    static int N = 110;
    static boolean[][] st = new boolean[N][N];
    static int[] dx = {0, 1, 0, -1};
    static int[] dy = {1, 0, -1, 0};
    static Queue<int[]> q = new LinkedList<>();

    
    public static void main(String[] args) throws Exception{
        Scanner s = new Scanner(System.in);
        int n = s.nextInt();
        int m = s.nextInt();
        
        int t = s.nextInt();
        
        while(t-- > 0) {
            int x = s.nextInt();
            int y = s.nextInt();
            q.add(new int[] {x, y});
            st[x][y] = true;
        }
        
        int k = s.nextInt();
        int cnt = 0;
        while(!q.isEmpty() && k-- >= 0) {
            int len = q.size();
            cnt += len;
            while(len-- > 0) {
                int[] d = q.poll();
                int x = d[0], y = d[1];
                for(int i = 0; i < 4; i++) {
                    int tX = x + dx[i], tY = y + dy[i];
                    if(tX >= 1 && tX <= n && tY >= 1 && tY <= m && !st[tX][tY]) {
                        st[tX][tY] = true;
                        q.add(new int[] {tX, tY});
                    }
                }
            }
        }
        
        System.out.println(cnt);
        
    }
}

第二题:小朋友崇拜圈

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class Main {

    static int N = (int)1e5 + 10;
    static int[] a = new int[N];
    static boolean[] st = new boolean[N];
    static int res, n, t;
    
    static void dfs(int x, int cnt) {
        if(st[x]) {
            if(a[x] == a[t]) {
                res = Math.max(res, cnt);
            }
            return;
        }
        
        st[x] = true;
        dfs(a[x], cnt+1);
        st[x] = false;
    }
    
    public static void main(String[] args) throws Exception{
        
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        
        n = Integer.parseInt(br.readLine());
        String[] s = br.readLine().split(" ");
        
        for(int i = 1; i <= n; i++) {
            a[i] = Integer.parseInt(s[i-1]);
        }
        
        
        for(int i = 1; i <= n; i++) {
            t = i;
            dfs(i, 0);
        }
        
        System.out.println(res);
    }
}

第三题:括号序列

第四题:砍竹子

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值