Problem:


Score : 800 points

Problem Statement

There is a pond with a rectangular shape.
The pond is divided into a grid with H rows and W columns of squares.
We will denote the square at the i-th row from the top and j-th column from the left by (i,\ j).

Some of the squares in the pond contains a lotus leaf floating on the water.
On one of those leaves, S, there is a frog trying to get to another leaf T.
The state of square (i,\ j) is given to you by a character a_{ij}, as follows:

. : A square without a leaf.

o : A square with a leaf floating on the water.

S : A square with the leaf S.

T : A square with the leaf T.

The frog will repeatedly perform the following action to get to the leaf T: "jump to a leaf that is in the same row or the same column as the leaf where the frog is currently located."

Snuke is trying to remove some of the leaves, other than S and T, so that the frog cannot get to the leaf T.
Determine whether this objective is achievable. If it is achievable, find the minimum necessary number of leaves to remove.

Constraints

2 ≤ H, W ≤ 100

a_{ij} is ., o, S or T.

There is exactly one S among a_{ij}.

There is exactly one T among a_{ij}.

Input

Input is given from Standard Input in the following format:

H W
a_{11} ... a_{1W}
:
a_{H1} ... a_{HW}

Output

If the objective is achievable, print the minimum necessary number of leaves to remove.
Otherwise, print -1 instead.

Sample Input 1

3 3
S.o
.o.
o.T

Sample Output 1

2

Remove the upper-right and lower-left leaves.

Sample Input 2

3 4
S...
.oo.
...T

Sample Output 2

0

Sample Input 3

4 3
.S.
.o.
.o.
.T.

Sample Output 3

-1

Sample Input 4

10 10
.o...o..o.
....o.....
....oo.oo.
..oooo..o.
....oo....
..o..o....
o..o....So
o....T....
....o.....
........oo

Sample Output 4

5



Sample input:
3 3
S.o
.o.
o.T


Sample output:
2

Submission status: Accepted

Solution code:
# https://tjkendev.github.io/procon-library/python/max_flow/dinic.html
# Dinic's algorithm
from collections import deque
class Dinic:
    def __init__(self, N):
        self.N = N
        self.G = [[] for i in range(N)]

    def add_edge(self, fr, to, cap):
        forward = [to, cap, None]
        forward[2] = backward = [fr, 0, forward]
        self.G[fr].append(forward)
        self.G[to].append(backward)

    def add_multi_edge(self, v1, v2, cap1, cap2):
        edge1 = [v2, cap1, None]
        edge1[2] = edge2 = [v1, cap2, edge1]
        self.G[v1].append(edge1)
        self.G[v2].append(edge2)

    def bfs(self, s, t):
        self.level = level = [None]*self.N
        deq = deque([s])
        level[s] = 0
        G = self.G
        while deq:
            v = deq.popleft()
            lv = level[v] + 1
            for w, cap, _ in G[v]:
                if cap and level[w] is None:
                    level[w] = lv
                    deq.append(w)
        return level[t] is not None

    def dfs(self, v, t, f):
        if v == t:
            return f
        level = self.level
        for e in self.it[v]:
            w, cap, rev = e
            if cap and level[v] < level[w]:
                d = self.dfs(w, t, min(f, cap))
                if d:
                    e[1] -= d
                    rev[1] += d
                    return d
        return 0

    def flow(self, s, t):
        flow = 0
        INF = 10**9 + 7
        G = self.G
        while self.bfs(s, t):
            *self.it, = map(iter, self.G)
            f = INF
            while f:
                f = self.dfs(s, t, INF)
                flow += f
        return flow


# coding: utf-8
# Your code here!
import sys
read = sys.stdin.read
readline = sys.stdin.readline

h,w = map(int,readline().split())
b = read().split()

#g = [[] for _ in range(h+w+2)]

S = h+w
T = h+w+1

D = Dinic(h+w+2)

for i in range(h):
    for j in range(w):
        if b[i][j] == "S":
            #print("S")
            sh,sw = i,j
            D.add_edge(S, i, 200)        
            D.add_edge(S, j+h, 200)        
            #g[S].append((i,200))
            #g[S].append((j+h,200))
        elif b[i][j] == "T":
            #print("T")
            th,tw = i,j
            D.add_edge(i, T, 200)        
            D.add_edge(j+h, T, 200)        
            #g[i].append((T,200))
            #g[j+h].append((T,200))
        elif b[i][j] == "o":
            #print("o")
            D.add_edge(i, j+h, 1)        
            D.add_edge(j+h, i, 1)        
            #g[i].append((j+h,1))
            #g[j+h].append((i,1))
            

if sh==th or sw==tw: print(-1)
else:
    print(D.flow(S,T))

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
sys.setrecursionlimit(1000)
from collections import *

class FordFulkerson:
    def __init__(self, N, edges): #edges: (s, t, c) sからtに向かう容量cの有向辺
        self.N = N
        self.G = defaultdict(lambda : defaultdict(int))
        
        for s, t, cap in edges:
            self.G[s][t] = cap
        
    def dfs(self, v, t, f):
        if v==t:
            return f
        
        self.used[v] = True
        
        for nv, cap in self.G[v].items():
            if not self.used[nv] and self.G[v][nv]>0:
                d = self.dfs(nv, t, min(f, self.G[v][nv]))
                
                if d>0:
                    self.G[v][nv] -= d
                    self.G[nv][v] += d
                    
                    return d
        
        return 0
    
    def max_flow(self, s, t):
        flow = 0
        
        while True:
            self.used = [False]*self.N
            f = self.dfs(s, t, 10**18)
        
            if f==0:
                return flow
        
            flow += f

H, W = map(int, input().split())
a = [list(input()[:-1]) for _ in range(H)]

for i in range(H):
    for j in range(W):
        if a[i][j]=='S':
            sx, sy = i, j
        
        if a[i][j]=='T':
            tx, ty = i, j

if sx==tx or sy==ty:
    print(-1)
    exit()
    
edges = []
edges.append((0, sx+1, 10**18))
edges.append((0, H+sy+1, 10**18))
edges.append((tx+1, H+W+1, 10**18))
edges.append((H+ty+1, H+W+1, 10**18))

for i in range(H):
    for j in range(W):
        if a[i][j]=='o':
            edges.append((i+1, H+j+1, 1))
            edges.append((H+j+1, i+1, 1))
    
ff = FordFulkerson(H+W+2, edges)
print(ff.max_flow(0, H+W+1))

Submission status: Accepted

Solution code:
import sys#if RE->suspect recursion limit error
from collections import deque
sys.setrecursionlimit(10000)

class Dinic:
    """max-flow-min-cut
    faster than ford-fulkerson algorithm
    O(|V||E|)
    """

    def __init__(self,V:int):
        """
        Arguments:
            V:num of vertex
            adj:adjedscent list(adj[from]=(to,capacity,id))
        """
        self.V = V
        self.adj=[[] for _ in range(V)]
        self.level=[-1]*self.V
        self.iter=[-1]*self.V

    def add_edge(self,fro:int,to:int,cap:int):
        """
        Arguments:
            fro:from
            to: to
            cap: capacity of the edge
            f: max flow value
        """
        #edge
        self.adj[fro].append([to,cap,len(self.adj[to])])
        #rev edge
        self.adj[to].append([fro,0,len(self.adj[fro])-1])

    def bfs(self,s:int):
        """ bfs from s
        use deque to bfs
        """
        self.level=[-1]*self.V
        Q=deque()
        self.level[s]=0
        Q.append(s)

        while Q:
            v = Q.pop()
            for i in range(len(self.adj[v])):
                (nex_id,nex_cap,nex_rev) = self.adj[v][i]
                if nex_cap>0 and self.level[nex_id]<-0:
                    self.level[nex_id] = self.level[v]+1
                    Q.append(nex_id)


    def dfs(self,v,t,f):

        """
        search increasing path
        """
        if v==t:
            return f

        for i in range(self.iter[v],len(self.adj[v])):
            self.iter[v]=i
            (nex_id,nex_cap,nex_rev) = self.adj[v][i]
            if nex_cap>0 and self.level[v]<self.level[nex_id]:
                d = self.dfs(nex_id,t,min(f,nex_cap))
                if d>0:
                    #decrease capacity to denote use it with d flow
                    self.adj[v][i][1]-=d
                    self.adj[nex_id][nex_rev][1]+=d
                    return d
        return 0

    def max_flow(self,s:int,t:int):
        """calculate maxflow from s to t
        """
        flow=0
        self.used = [False]*self.V
        #while no increasing path is found
        while True:
            self.bfs(s)
            self.iter=[0]*self.V
            f = self.dfs(s,t,float("inf"))
            if f==0:
                return flow
            else:
                flow+=f

H,W = map(int,input().split())
grid=[[v for v in input()] for _ in range(H)]

F = Dinic(H+W+2)
for i in range(H):
    for j in range(W):
        if grid[i][j]=="S":
            sy,sx = i,j
            F.add_edge(0,i+1,float("inf"))
            F.add_edge(0,H+j+1,float("inf"))
        elif grid[i][j]=="T":
            gy,gx=i,j
            F.add_edge(i+1,H+W+1,float("inf"))
            F.add_edge(H+j+1,H+W+1,float("inf"))
        elif grid[i][j]=="o":
            F.add_edge(i+1,H+j+1,1)
            F.add_edge(H+j+1,i+1,1)

if sy==gy or sx==gx:
    print(-1)
    exit()
print(F.max_flow(0,H+W+1))

Submission status: Accepted

Solution code:
class FordFulkerson:
    """max-flow-min-cut
    O(F|E|)
    """

    def __init__(self,V:int):
        """
        Arguments:
            V:num of vertex
            adj:adjedscent list(adj[from]=(to,capacity,id))
        """
        self.V = V
        self.adj=[[] for _ in range(V)]
        self.used=[False]*V

    def add_edge(self,fro:int,to:int,cap:int):
        """
        Arguments:
            fro:from
            to: to
            cap: capacity of the edge
            f: max flow value
        """
        #edge
        self.adj[fro].append([to,cap,len(self.adj[to])])
        #rev edge
        self.adj[to].append([fro,0,len(self.adj[fro])-1])

    def dfs(self,v,t,f):
        """
        search increasing path
        """
        if v==t:
            return f
        self.used[v]=True
        for i in range(len(self.adj[v])):
            (nex_id,nex_cap,nex_rev) = self.adj[v][i]
            if not self.used[nex_id] and nex_cap>0:
                d = self.dfs(nex_id,t,min(f,nex_cap))
                if d>0:
                    #decrease capacity to denote use it with d flow
                    self.adj[v][i][1]-=d
                    self.adj[nex_id][nex_rev][1]+=d
                    return d
        return 0

    def max_flow(self,s:int,t:int):
        """calculate maxflow from s to t
        """
        flow=0
        self.used = [False]*self.V
        #while no increasing path is found
        while True:
            self.used = [False]*self.V
            f = self.dfs(s,t,float("inf"))
            if f==0:
                return flow
            else:
                flow+=f


H,W = map(int,input().split())
grid=[[v for v in input()] for _ in range(H)]

F = FordFulkerson(H+W+2)
for i in range(H):
    for j in range(W):
        if grid[i][j]=="S":
            sy,sx = i,j
            F.add_edge(0,i+1,float("inf"))
            F.add_edge(0,H+j+1,float("inf"))
        elif grid[i][j]=="T":
            gy,gx=i,j
            F.add_edge(i+1,H+W+1,float("inf"))
            F.add_edge(H+j+1,H+W+1,float("inf"))
        elif grid[i][j]=="o":
            F.add_edge(i+1,H+j+1,1)
            F.add_edge(H+j+1,i+1,1)

if sy==gy or sx==gx:
    print(-1)
    exit()
print(F.max_flow(0,H+W+1))

Submission status: Accepted

Solution code:
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians, log
from itertools import accumulate, permutations, combinations, product
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left
from fractions import gcd
from heapq import heappush, heappop
from functools import reduce
import networkx as nx
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def ZIP(n): return zip(*(MAP() for _ in range(n)))
sys.setrecursionlimit(10 ** 9)
INF = 10**10
mod = 10 ** 9 + 7

H, W = MAP()
a = [list(input()) for _ in range(H)]
G = nx.Graph()
G.add_nodes_from(range(0, H+W+2))

for i in range(H):
    for j in range(W):
        if a[i][j] == "S":
            sy, sx = i, j
            G.add_edge(0, i+1, capacity=INF)
            G.add_edge(0, H+j+1, capacity=INF)
        elif a[i][j] == "T":
            gy, gx = i, j
            G.add_edge(i+1, H+W+1, capacity=INF)
            G.add_edge(H+j+1, H+W+1, capacity=INF)
        elif a[i][j] == "o":
            G.add_edge(i+1, H+j+1, capacity=1)
            G.add_edge(H+j+1, i+1, capacity=1)

if sy == gy or sx == gx:
	print(-1)
	exit()

print(nx.maximum_flow_value(G, 0, H+W+1))

Submission status: Accepted

Solution code:
from networkx import*
H, W = map(int, input().split())
X = [[a for a in input()] for _ in range(H)]
G = Graph()
G.add_nodes_from(range(-2, H + W))
for i in range(H):
    for j in range(W):
        if X[i][j] == "o":
            G.add_edge(i, j + H, capacity = 1)
        elif X[i][j] == "S":
            si, sj = i, j
        elif X[i][j] == "T":
            ti, tj = i, j
        
G.add_edge(-1, si, capacity = 1 << 20)
G.add_edge(-1, sj + H, capacity = 1 << 20)
G.add_edge(-2, ti, capacity = 1 << 20)
G.add_edge(-2, tj + H, capacity = 1 << 20)

mf = maximum_flow(G, -1, -2)[0]
print(-1 if mf > 1 << 19 else mf)

Submission status: Accepted

Solution code:
# graph = [{} for _ in range(V)]
# when there is an edge u -> v (maxflow f)
#  graph[u][v] = f
#  graph[v][u] = f (if undirected) 0 (if directed)

class FordFulkerson():
    def __init__(self, start, finish, graph, INF=10**18):
        self.INF = INF
        self.start = start
        self.finish = finish
        self.graph = graph
        self.N = len(graph)

    def dfs(self):
        self.Flow = [self.INF]*self.N
        self.used = [False]*self.N
        self.Par = [-1]*self.N
        self.stack = [self.start]
        self.used[self.start] = True
        while self.stack:
            v = self.stack.pop()
            if v == self.finish:
                d = self.Flow[v]
                while v != self.start:
                    nv = self.Par[v]
                    self.graph[nv][v] -= d
                    self.graph[v][nv] += d
                    v = nv
                return d
            for i, (nv, ncap) in enumerate(self.graph[v].items()):
                if not self.used[nv] and ncap > 0:
                    self.used[nv] = True
                    self.stack.append(nv)
                    self.Par[nv] = v
                    self.Flow[nv] = min(self.Flow[v], ncap)
        return 0

    # solve
    def flow(self):
        flow = 0
        while True:
            f = self.dfs()
            if f == 0: return flow
            flow += f


import sys
input = sys.stdin.readline

INF = 10**18

H, W = map(int, input().split())
V = H+W


def make():
    state = [list(input().rstrip()) for _ in range(H)]
    graph = [{} for _ in range(V+2)]

    start = V
    finish = V+1

    for h in range(H):
        for w in range(W):
            u, v = h, w+H
            if state[h][w] == "o":
                graph[u][v] = 1
                graph[v][u] = 1
            if state[h][w] == "S":
                graph[v][start] = INF
                graph[start][v] = INF
                graph[u][start] = INF
                graph[start][u] = INF
            if state[h][w] == "T":
                graph[u][finish] = INF
                graph[finish][u] = INF
                graph[v][finish] = INF
                graph[finish][v] = INF
    
    return graph, start, finish



def main():
    graph, start, finish = make()
    ff = FordFulkerson(start, finish, graph)
    ans = ff.flow()

    if ans > INF//2:
        print(-1)
    else:
        print(ans)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
# AOJ GRL_6_A "Maximum Flow"
# Ford-Fulkerson method

import sys
input = sys.stdin.readline

INF = 10**18

H, W = map(int, input().split())
V = H+W


def make():
    state = [list(input().rstrip()) for _ in range(H)]
    graph = [{} for _ in range(V+2)]

    start = V
    finish = V+1

    for h in range(H):
        for w in range(W):
            u, v = h, w+H
            if state[h][w] == "o":
                graph[u][v] = 1
                graph[v][u] = 1
            if state[h][w] == "S":
                graph[v][start] = INF
                graph[start][v] = INF
                graph[u][start] = INF
                graph[start][u] = INF
            if state[h][w] == "T":
                graph[u][finish] = INF
                graph[finish][u] = INF
                graph[v][finish] = INF
                graph[finish][v] = INF
    
    return graph, start, finish


def dfs2(start, finish, graph):
    Flow = [INF]*len(graph)
    used = [False]*len(graph)
    Par = [-1]*len(graph)
    stack = [start]
    used[start] = True
    while stack:
        v = stack.pop()
        if v == finish:
            d = Flow[v]
            while v != start:
                nv = Par[v]
                graph[nv][v] -= d
                graph[v][nv] += d
                v = nv
            return d, graph
        for i, (nv, ncap) in enumerate(graph[v].items()):
            if not used[nv] and ncap > 0:
                used[nv] = True
                stack.append(nv)
                Par[nv] = v
                Flow[nv] = min(Flow[v], ncap)
    return 0, graph

# solve
def max_flow(start, finish, graph):
    flow = 0
    while True:
        f, graph = dfs2(start, finish, graph)
        if f == 0: return flow
        flow += f


def main():
    graph, start, finish = make()
    ans = max_flow(start, finish, graph)

    if ans > INF//2:
        print(-1)
    else:
        print(ans)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
from collections import deque


class Dinic:
    def __init__(self, n: int):
        self.INF = 10**9 + 7
        self.n = n
        self.graph = [[] for _ in range(n)]
 
    def add_edge(self, _from: int, to: int, capacity: int):
        """残余グラフを構築
        1. _fromからtoへ向かう容量capacityの辺をグラフに追加する
        2. toから_fromへ向かう容量0の辺をグラフに追加する
        """
        forward = [to, capacity, None]
        forward[2] = backward = [_from, 0, forward]
        self.graph[_from].append(forward)
        self.graph[to].append(backward)
 
    def bfs(self, s: int, t: int):
        """capacityが正の辺のみを通ってsからtに移動可能かどうかBFSで探索
        level: sからの最短路の長さ
        """
        self.level = [-1] * self.n
        q = deque([s])
        self.level[s] = 0
        while q:
            _from = q.popleft()
            for to, capacity, _ in self.graph[_from]:
                if capacity > 0 and self.level[to] < 0:
                    self.level[to] = self.level[_from] + 1
                    q.append(to)
 
    def dfs(self, _from: int, t: int, f: int) -> int:
        """流量が増加するパスをDFSで探索
        BFSによって作られた最短路に従ってfを更新する
        """
        if _from == t:
            return f
        for edge in self.itr[_from]:
            to, capacity, reverse_edge = edge
            if capacity > 0 and self.level[_from] < self.level[to]:
                d = self.dfs(to, t, min(f, capacity))
                if d > 0:
                    edge[1] -= d
                    reverse_edge[1] += d
                    return d
        return 0
 
    def max_flow(self, s: int, t: int):
        """s-tパス上の最大流を求める
        計算量: O(|E||V|^2)
        """
        flow = 0
        while True:
            self.bfs(s, t)
            if self.level[t] < 0:
                break
            self.itr = list(map(iter, self.graph))
            f = self.dfs(s, t, self.INF)
            while f > 0:
                flow += f
                f = self.dfs(s, t, self.INF)
        return flow


h, w = map(int, input().split())
a = [list(input()) for i in range(h)]

di = Dinic(h + w + 2)
for i in range(h):
    for j in range(w):
        if a[i][j] == "o":
            di.add_edge(i, h + j, 1)
            di.add_edge(h + j, i, 1)
        if a[i][j] == "S":
            di.add_edge(h + w, i, 10 ** 5)
            di.add_edge(h + w, h + j, 10 ** 5)
        if a[i][j] == "T":
            di.add_edge(i, h + w + 1, 10 ** 5)
            di.add_edge(h + j, h + w + 1, 10 ** 5)

ans = di.max_flow(h + w, h + w + 1)
if ans >= 10 ** 5:
    print(-1)
else:
    print(ans)

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
H, W = map(int, input().split())
a = [list(input())[: -1] for _ in range(H)]
c = H + W - 1
class FordFulkerson:
    def __init__(self, N):
        self.N = N
        self.G = [[] for i in range(N)]

    def add_edge(self, fr, to, cap):
        forward = [to, cap, None]
        forward[2] = backward = [fr, 0, forward]
        self.G[fr].append(forward)
        self.G[to].append(backward)

    def add_multi_edge(self, v1, v2, cap1, cap2):
        edge1 = [v2, cap1, None]
        edge1[2] = edge2 = [v1, cap2, edge1]
        self.G[v1].append(edge1)
        self.G[v2].append(edge2)

    def dfs(self, v, t, f):
        if v == t:
            return f
        used = self.used
        used[v] = 1
        for e in self.G[v]:
            w, cap, rev = e
            if cap and not used[w]:
                d = self.dfs(w, t, min(f, cap))
                if d:
                    e[1] -= d
                    rev[1] += d
                    return d
        return 0

    def flow(self, s, t):
        flow = 0
        f = INF = c
        N = self.N
        while f:
            #print(f)
            self.used = [0]*N
            f = self.dfs(s, t, INF)
            flow += f
        return flow
flk = FordFulkerson(H * W * 2 + H + W + 1)
b = H * W
s = 0
t = 0
for i in range(H):
  for j in range(W):
    if a[i][j] != ".":
      flk.add_edge(b + i * W + j, b * 2 + i, c)
      flk.add_edge(b * 2 + i, i * W + j, c)
for j in range(W):
  for i in range(H):
    if a[i][j] != ".":
      flk.add_edge(b + i * W + j, b * 2 + H + j, c)
      flk.add_edge(b * 2 + H + j, i * W + j, c)
for i in range(H):
  for j in range(W):
    if a[i][j] != ".":
      flk.add_edge(i * W + j, b + i * W + j, 1)
    if a[i][j] == "S": s = b + i * W + j
    if a[i][j] == "T": t = i * W + j
if (s - b) % W != t % W and ((s - b) // W != t // W):
  if sum([x.count("o") for x in a]) == H * W - 2: print(min(H, W) * 2 - 2)
  else: print(flk.flow(s, t))
else: print(-1)

Submission status: Accepted

Solution code:
from collections import deque


class Dinic:
    def __init__(self, v, inf=10**9 + 7):
        self.V = v
        self.inf = inf
        self.G = [list() for _ in range(v)]
        self.level = [-1 for _ in range(v)]
        self.iter = [0] * v

    def addedge(self, fr, to, cap):
        """
        G[fr] = [to, cap, rev]
        """
        go = [to, cap, None]
        go[2] = back = [fr, 0, go]
        self.G[fr].append(go)
        self.G[to].append(back)

    def bfs(self, st, en):
        q = deque([st])
        self.level = [-1 for _ in range(self.V)]
        self.level[st] = 0
        while q:
            cur = q.popleft()
            for x, cap, _ in self.G[cur]:
                if cap and self.level[x] < 0:
                    self.level[x] = self.level[cur] + 1
                    q.append(x)
        return self.level[en] > 0

    def dfs(self, v, t, f):
        if v == t:
            return f
        for e in self.iter[v]:
            w, cap, rev = e
            if cap and self.level[v] < self.level[w]:
                d = self.dfs(w, t, min(f, cap))
                if d:
                    e[1] -= d
                    rev[1] += d
                    return d
        return 0

    def flow(self, s, t):
        flow = 0
        while self.bfs(s, t):
            self.iter = list(map(iter, self.G))
            f = self.dfs(s, t, self.inf)
            while f:
                flow += f
                f = self.dfs(s, t, self.inf)
        return flow
      
      
      
H, W = map(int, input().split())
dinic = Dinic(200)
for y in range(H):
  s = input()
  for x in range(W):
    if s[x] == 'o':
      dinic.addedge(y, x+100, 1)
      dinic.addedge(x+100, y, 1)
    elif s[x] == 'S':
      sy, sx = y, x
      dinic.addedge(y, x+100, 10**5)
      dinic.addedge(x+100, y, 10**5)
    elif s[x] == 'T':
      ty, tx = y, x
      dinic.addedge(y, x+100, 10**5)
      dinic.addedge(x+100, y, 10**5)
print(-1 if sy == ty or sx == tx else dinic.flow(sy, ty))

Submission status: Accepted

Solution code:
# Dinic's algorithm
from collections import deque
class Dinic:
    def __init__(self, N):
        self.N = N
        self.G = [[] for i in range(N)]

    def add_edge(self, fr, to, cap):
        forward = [to, cap, None]
        forward[2] = backward = [fr, 0, forward]
        self.G[fr].append(forward)
        self.G[to].append(backward)

    def add_multi_edge(self, v1, v2, cap1, cap2):
        edge1 = [v2, cap1, None]
        edge1[2] = edge2 = [v1, cap2, edge1]
        self.G[v1].append(edge1)
        self.G[v2].append(edge2)

    def bfs(self, s, t):
        self.level = level = [None]*self.N
        deq = deque([s])
        level[s] = 0
        G = self.G
        while deq:
            v = deq.popleft()
            lv = level[v] + 1
            for w, cap, _ in G[v]:
                if cap and level[w] is None:
                    level[w] = lv
                    deq.append(w)
        return level[t] is not None

    def dfs(self, v, t, f):
        if v == t:
            return f
        level = self.level
        for e in self.it[v]:
            w, cap, rev = e
            if cap and level[v] < level[w]:
                d = self.dfs(w, t, min(f, cap))
                if d:
                    e[1] -= d
                    rev[1] += d
                    return d
        return 0

    def flow(self, s, t):
        flow = 0
        INF = 10**9 + 7
        G = self.G
        while self.bfs(s, t):
            *self.it, = map(iter, self.G)
            f = INF
            while f:
                f = self.dfs(s, t, INF)
                flow += f
        return flow

H,W=map(int,input().split())
a=[]
for i in range(H):
    a.append(input())

leaf=[]
for i in range(H):
    for j in range(W):
        if a[i][j]=="o":
            leaf.append((i,j))
        elif a[i][j]=="S":
            s=(i,j)
        elif a[i][j]=="T":
            t=(i,j)

inf=300
L=Dinic(H+W+2+2*len(leaf))
for i in range(len(leaf)):
    x,y=leaf[i]
    X,Y=x+1,y+H+1
    index=2*i+H+W+1
    L.add_edge(X,index,inf)
    L.add_edge(Y,index,inf)
    L.add_edge(index,index+1,1)
    L.add_edge(index+1,X,inf)
    L.add_edge(index+1,Y,inf)

i,j=s
L.add_edge(0,i+1,inf)
L.add_edge(0,j+H+1,inf)
i,j=t
L.add_edge(i+1,H+W+2+2*(len(leaf))-1,inf)
L.add_edge(j+H+1,H+W+2+2*(len(leaf))-1,inf)
ans=L.flow(0,H+W+2+2*(len(leaf))-1)
print(ans if inf>ans else -1)

Submission status: Accepted

Solution code:
def main():
    # 行先、上限、逆辺
    def add_edge(From, to, cap):
        g[From][to] = cap
        g[to][-From-1] = 0

    def max_flow(s, t):
        flow = 0
        while True:
            used = [False]*n
            used2 = [0]*n
            q = [(s, 10**6)]
            ans = [0]
            while q:
                v, f = q[-1]
                a = ans[0]
                if a == 0:
                    if v == t:
                        ans[0] = f
                        continue
                    gkv, gv = gkey[v], g[v]
                    l, used[v] = len(gkv), True
                    while True:
                        i = used2[v]
                        used2[v] += 1
                        if i < l:
                            to = gkv[i]
                            cap, to2 = gv[to], [to, -to-1][to < 0]
                            if (not used[to2]) and cap:
                                q.append((to2, min(f, cap)))
                                break
                        else:
                            q.pop()
                            ans[0] = 0
                            break
                else:
                    q.pop()
                    if q:
                        v = q[-1][0]
                        i = used2[v]-1
                        to = gkey[v][i]
                        g[v][to] -= a
                        g[[to, -to-1][to < 0]][-v-1] += a
            if not ans[0]:
                return flow
            flow += ans[0]

    h, w = map(int, input().split())
    n = h+w+2
    g = [dict() for _ in range(n)]
    for i in range(h):
        A = input()
        for j in range(w):
            if A[j] == "o":
                add_edge(i, j+h, 1)
                add_edge(j+h, i, 1)
            elif A[j] == "S":
                add_edge(h+w, i, 10**6)
                add_edge(h+w, j+h, 10**6)
            elif A[j] == "T":
                add_edge(i, h+w+1, 10**6)
                add_edge(j+h, h+w+1, 10**6)
    gkey = [list(i.keys()) for i in g]

    ans = max_flow(h+w, h+w+1)
    if ans >= 10**6:
        print(-1)
    else:
        print(ans)


main()

Submission status: Accepted

Solution code:
def main():
    # 行先、上限、逆辺
    def add_edge(From, to, cap):
        g[From][to] = cap
        g[to][-From-1] = 0

    def max_flow(s, t):
        def dfs():
            while q:
                v, t, f = q[-1]
                if ans[0] == 0:
                    if v == t:
                        ans[0] = f
                        continue
                    used[v] += 1
                    while True:
                        i = used2[v]
                        used2[v] += 1
                        if i < len(gkey[v]):
                            to = gkey[v][i]
                            cap = g[v][to]
                            if to < 0:
                                to2 = -to-1
                            else:
                                to2 = to
                            if used[to2] or cap == 0:
                                continue
                            q.append((to2, t, min(f, cap)))
                            break
                        else:
                            q.pop()
                            ans[0] = 0
                            break
                else:
                    q.pop()
                    if q:
                        v, t, f = q[-1]
                        i = used2[v]-1
                        to = gkey[v][i]
                        if to < 0:
                            to2 = -to-1
                        else:
                            to2 = to
                        g[v][to] -= ans[0]
                        g[to2][-v-1] += ans[0]

        flow = 0
        while True:
            used = [0]*n
            used2 = [0]*n
            q = [(s, t, 10**6)]
            ans = [0]
            dfs()
            if not ans[0]:
                return flow
            flow += ans[0]

    h, w = map(int, input().split())
    n = h+w+2
    g = [dict() for _ in range(n)]
    for i in range(h):
        A = input()
        for j in range(w):
            if A[j] == "o":
                add_edge(i, j+h, 1)
                add_edge(j+h, i, 1)
            elif A[j] == "S":
                add_edge(h+w, i, 10**6)
                add_edge(h+w, j+h, 10**6)
            elif A[j] == "T":
                add_edge(i, h+w+1, 10**6)
                add_edge(j+h, h+w+1, 10**6)
    gkey = [list(i.keys()) for i in g]

    ans = max_flow(h+w, h+w+1)
    if ans >= 10**6:
        print(-1)
    else:
        print(ans)


main()