第十三届JAVAB组决赛——6.迷宫
import java.io.*;
import java.util.*;
public class Main{
public static BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
public static PrintWriter stdOut = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
public static final int N = 2010;
public static int[] dist = new int[N * N];
public static int[] h = new int[N * N];
public static int[] e = new int[2 * N];
public static int[] ne = new int[2 * N];
public static int n, m, idex;
public static void add(int a, int b) {
e[idex] = b; ne[idex] = h[a]; h[a] = idex++;
}
public static void main(String[] args) throws IOException{
String[] sp = stdIn.readLine().split(" ");
n = Integer.parseInt(sp[0]); m = Integer.parseInt(sp[1]);
Arrays.fill(dist, Integer.MAX_VALUE);
Arrays.fill(h, -1);
dist[n * n - 1] = 0;
while(m-- > 0) {
sp = stdIn.readLine().split(" ");
int x1 = Integer.parseInt(sp[0]); int y1 = Integer.parseInt(sp[1]);
int x2 = Integer.parseInt(sp[2]); int y2 = Integer.parseInt(sp[3]);
x1--; y1--; x2--; y2--;
int c1 = x1 * n + y1; int c2 = x2 * n + y2;
add(c1, c2); add(c2, c1);
}
Queue<Integer> q = new LinkedList<Integer>();
q.add(n * n - 1);
while(!q.isEmpty()) {
int c = q.poll();
int x = c / n; int y = c % n;
for(int i = h[c]; i != -1; i = ne[i]) {
int j = e[i];
if(dist[j] > dist[c] + 1) {
dist[j] = dist[c] + 1;
q.add(j);
}
}
int[] dx = {1,-1,0,0}; int[] dy = {0,0,1,-1};
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) {
int j = a * n + b;
if(dist[j] > dist[c] + 1) {
dist[j] = dist[c] + 1;
q.add(j);
}
}
}
}
double sum = 0;
for(int i = 0; i < n * n; i++) {
sum += dist[i];
}
stdOut.println(String.format("%.2f", sum / (n * n)));
stdOut.flush();
}
}