原题链接:蓝桥杯2022年第十三届决赛真题-迷宫
import java.util.*; import java.io.*; public class Main{ static final int N = 2010, INF = 0x3f3f3f3f, M = N * N + N; static int n, m; static List<Integer>[] list = new ArrayList[M]; static int[] dx = {-1, 0, 1, 0}; static int[] dy = {0, 1, 0, -1}; static int[] dist = new int[M]; static boolean[] st = new boolean[M]; public static void main(String[] args) throws Exception{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String[] str = br.readLine().split(" "); n = Integer.parseInt(str[0]); m = Integer.parseInt(str[1]); for(int i=0 ; i<M ; i++) list[i] = new ArrayList<>(); for(int i=0 ; i<m ; i++) { str = br.readLine().split(" "); int x1 = Integer.parseInt(str[0]); int y1 = Integer.parseInt(str[1]); int x2 = Integer.parseInt(str[2]); int y2 = Integer.parseInt(str[3]); x1--; y1--; x2--; y2--; list[get(x1, y1)].add(get(x2, y2)); list[get(x2, y2)].add(get(x1, y1)); } bfs(); double res = 0; for(int i=0 ; i<n ; i++) for(int j=0 ; j<n ; j++) res += dist[get(i, j)]; res /= n * n; System.out.printf("%.2f", res); } public static void bfs() { Arrays.fill(dist, INF); Queue<Integer> q = new LinkedList<>(); q.add(get(n - 1, n - 1)); dist[get(n - 1, n - 1)] = 0; while(q.size() > 0) { int t = q.remove(); int x = t / n; int y = t % n; st[t] = false; for(int v: list[t]) { int a = v / n; int b = v % n; if(dist[get(a, b)] > dist[get(x, y)] + 1) { dist[get(a, b)] = dist[get(x, y)] + 1; if(!st[get(a, b)]) { q.add(get(a, b)); st[get(a, b)] = true; } } } for(int i=0 ; i<4 ; i++) { int a = x + dx[i]; int b = y + dy[i]; if(a < 0 || a >= n || b < 0 || b >= n) continue; if(dist[get(a, b)] > dist[get(x, y)] + 1) { dist[get(a, b)] = dist[get(x, y)] + 1; if(!st[get(a, b)]) { q.add(get(a, b)); st[get(a, b)] = true; } } } } } public static int get(int x, int y) { return x * n + y; } }
0.0分
3 人评分
C语言网提供由在职研发工程师或ACM蓝桥杯竞赛优秀选手录制的视频教程,并配有习题和答疑,点击了解:
一点编程也不会写的:零基础C语言学练课程
解决困扰你多年的C语言疑难杂症特性的C语言进阶课程
从零到写出一个爬虫的Python编程课程
只会语法写不出代码?手把手带你写100个编程真题的编程百练课程
信息学奥赛或C++选手的 必学C++课程
蓝桥杯ACM、信息学奥赛的必学课程:算法竞赛课入门课程
手把手讲解近五年真题的蓝桥杯辅导课程
发表评论 取消回复