📢📢📢哈喽,大家好呀,又到了刷题的时间了,来看今天的题目吧~
⛄⛄⛄灌溉⛄⛄⛄
📋问题描述
![](https://img-blog.csdnimg.cn/img_convert/e9c1ee1df01ac82691f2b6abd82d1101.png)
❓思路分享
⛄这是一道bfs模板题,但是模板题自己写起来还是老是出错,唉,还得多练两道啊😭
📗参考代码
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
/**
* @ClassName 灌溉
* @Author @浅夜
* @Date 2023/3/22 20:37
* @Version 1.0
*/
public class 灌溉 {
static int[] dx = {1, -1, 0, 0};
static int[] dy = {0, 0, 1, -1};
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int ans = 0;
int n = sc.nextInt();
int m = sc.nextInt();
boolean[][] st = new boolean[n][m];
int t = sc.nextInt(); //出水管的数量
ans = t; //开始已经有t个出水管
Queue<int[]> q = new LinkedList<>();
for(int i = 0; i < t; i++){
int r = sc.nextInt();
int c = sc.nextInt();
st[r-1][c-1] = true;
q.offer(new int[]{r-1,c-1});
}
int k = sc.nextInt();
while(k > 0 && ! q.isEmpty()){
k--;
int size = q.size();
while(size-- > 0){
int[] tmp = q.poll();
int x = tmp[0],y = tmp[1];
for(int i = 0; i < 4; i++){
int newX = x + dx[i];
int newY = y + dy[i];
if(newX >=0 && newX < n && newY >=0 && newY < m){
q.offer(new int[] {newX,newY});
ans++;
st[newX][newY] = true;
}
}
}
}
System.out.println(ans);
}
}
![](https://img-blog.csdnimg.cn/img_convert/07bdef8a0c539c8f7a911f1541d2611a.png)
💨💨💨小朋友崇拜圈💨💨💨
📋问题描述
![](https://img-blog.csdnimg.cn/img_convert/c3aee5cbdac2ae1b9d9871eb5e6e601a.png)
输入
9
3 4 2 5 3 8 4 6 9
❓思路分享
💨我们先将崇拜关系初始化成一个数组,然后遍历数组的每个元素,dfs求崇拜圈的长度,回到开始的小朋友时,循环结束。
💨有一点需要注意,就是当小朋友的崇拜关系形成了闭环,如1 -> 2 -> 3 -> 2 -> 3 -> 2...这种情况应该特判。
📗参考代码
import java.util.Scanner;
/**
* @ClassName 小朋友崇拜圈
* @Author @浅夜
* @Date 2023/3/22 21:55
* @Version 1.0
*/
public class 小朋友崇拜圈 {
static int[] a;
static int n;
public static void main(String[] args) {
int max = 0;
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
a = new int[n + 1];
for (int i = 1; i <= n; ++i) {
a[i] = sc.nextInt();
}
for (int i = 1; i <= n; i++) {
int length = dfs(i);
if(max < length) max = length;
}
System.out.println(max);
}
static int dfs(int i) {
int key = a[i]; //第i个小朋友崇拜的小朋友
int length = 1; //崇拜圈初始长度
while (key != i) { //回到驾驶的小朋友时,循环结束
key = a[key];
length ++;
if(length > n) return 0;
}
return length;
}
}
![](https://img-blog.csdnimg.cn/img_convert/cb14af5b3f27a2192df4f0add9eefbce.png)
🍬🍬🍬括号序列🍬🍬🍬
📋问题描述
![](https://img-blog.csdnimg.cn/img_convert/4429752d19404509aece8d29d19d7e84.png)
输入
((()
输出
5
太难啦太难了,只做了两道题,今天就到这里吧,后面的题解都看不懂呜呜呜