// Solution to "Zoo paths". The DFS was taken almost verbatim from the // Wikipedia article on "Tarjan's strongly connected components algorithm". import java.util.*; // One node in the DFS: class Node { int id; // input row # int index, low, comp; // DFS index, lowest reachable node, component # ArrayList nbr; // edges boolean stack; // is this waiting to be labeled with a component #? public Node(int i) { id = i; index = -1; stack = false; low = -1; nbr = new ArrayList(); comp = -1; } } public class Zoo_bob { public static Scanner in; public static int n; public static int[][]p; public static Node[] nd; public static int index; public static int comp; public static Stack stack; public static void main(String[] args) { in = new Scanner(System.in); n = in.nextInt(); p = new int[n][n]; nd = new Node[n]; for (int i = 0; i < n; i++) { nd[i] = new Node(i); for (int j = 0; j < n; j++) { p[i][j] = in.nextInt(); if (p[i][j] == 1) { nd[i].nbr.add(j); } } } stack = new Stack(); index = 0; comp = 0; for (int i = 0; i < n; i++) { if (nd[i].index == -1) { sc(i); } } int answer = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (i==j) continue; if (p[i][j]==1) continue; if (nd[i].comp >= nd[j].comp) answer++; } } System.out.println(answer); } public static void sc(int v) { nd[v].low = index; nd[v].index = index++; nd[v].stack = true; stack.push(v); for (Integer w:nd[v].nbr) { if (nd[w].index == -1) { sc(w); nd[v].low = Math.min(nd[v].low,nd[w].low); } else if (nd[w].stack) { nd[v].low = Math.min(nd[v].low,nd[w].index); } } if (nd[v].low == nd[v].index) { int w; do { w = stack.pop(); nd[w].comp = comp; nd[w].stack = false; } while (w != v); comp++; } } }