usaco why did the cow cross the road iii silver java
//sample input
3 3 3
2 2 2 3
3 3 3 2
3 3 2 3
3 3
2 2
2 3
//CODE (2021/1/18) YY/MM/DD
import java.util.*;
import java.io.*;
public class Main {
static field[][] farm;
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner (new File("countcross.in"));
int n = sc.nextInt();//n x n grid
int k = sc.nextInt();// k cows
int r = sc.nextInt();// r roads
farm = new field[n][n];
for (int i = 0; i < n; i++) Arrays.fill(farm[i], new field());
for (int i = 0; i < r; i++) setRoad(new position(sc.nextInt(), sc.nextInt()),
new position(sc.nextInt(), sc.nextInt()));
//floodFill
int no1 = 0;
for (int x = 0; x < n; x++ ){
for (int y = 0; y < n; y++){
if (!farm[x][y].visited){
floodFill(x, y, farm[x][y], no1);
no1++;
}
}
}
no1--;
int[] cows = new int[no1];
for (int i = 0; i < k; i++){
int x = sc.nextInt();
int y = sc.nextInt();
int index = farm[x-1][y-1].fieldNum;
cows[index - 1]++;
}
int answer = 0;
for (int i = 1; i < cows.length; i++){// when i = 0, it is in the default group, which means that it requires no road.
answer += k - cows[i];
}
PrintWriter out = new PrintWriter(new File("countcross.out"));
out.println(answer);
out.close();
sc.close();
}
static void floodFill(int x, int y, field thisF, int no1){
if (x < 0 || y < 0 || x >= farm.length || y >= farm[0].length) return; // Out of bound
if (thisF.visited) return; //visited
thisF = farm[x][y];
thisF.visited = true;
thisF.fieldNum = no1;
if (!thisF.fence[field.north]) floodFill(x, y+1, farm[x][y], no1);
if (!thisF.fence[field.south]) floodFill(x, y-1, farm[x][y], no1);
if (!thisF.fence[field.east]) floodFill(x+1, y, farm[x][y], no1);
if (!thisF.fence[field.west]) floodFill(x-1, y, farm[x][y], no1);
}
static void setRoad(position from, position to){
int dirF = from.pointTo(to);
int dirT = to.pointTo(from);
farm[from.x - 1][from.y - 1].fence[dirF] = true;
farm[to.x - 1][to.y - 1].fence[dirT] = true;
}
}
class field {
public boolean visited = false;
public int fieldNum = -1;
public boolean[] fence = new boolean[4];//NSWE
public field(){
}
static final int north = 0;
static final int south = 1;
static final int west = 2;
static final int east = 3;
}
class position {
public int x;
public int y;
public position(int x, int y){
this.x = x;
this.y = y;
}
public int pointTo(position a){
if (a.x > this.x) return field.east; if (a.x < this.x) return field.west;//x
if (a.y > this.y) return field.north; if (a.y < this.y) return field.south;//y
System.out.println("ERROR: poinTo");
return -1;
}
}
//Output:
2