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

Solution (Python):
from networkx import*
H,*S=open(0)
H,W=map(int,H.split())
g=Graph()
a=g.add_edges_from
for i in range(m:=H*W):a([[M:=m*2,h:=i//W],[M,w:=i%W+m]]*((c:=S[h][w-m])=='S')+[[h,I:=m*3],[w,I]]*(c=='T'),capacity=I),a([[h,w],[w,h]]*(c>'T'),capacity=1)
f,_=minimum_cut(g,M,I)
print(-(f>M)or f)

Solution (Python):
from networkx import*
H,*S=open(0)
H,W=map(int,H.split())
g=Graph()
a=g.add_edges_from
for i in range(m:=H*W):a([[M:=m*2,h:=i//W],[M,w:=i%W+m]]*((c:=S[h][w-m])=='S')+[[h,I:=m*3],[w,I]]*(c=='T'),capacity=I),a([[h,w],[w,h]]*(c>'T'),capacity=1)
print([-1,f:=minimum_cut(g,M,I)[0]][f<I])

Solution (Python):
from networkx import*
H,*S=open(0)
H,W=map(int,H.split())
g=Graph()
for i in range(m:=H*W):g.add_weighted_edges_from([[m*2,h:=i//W,I:=m*3],[m*2,w:=i%W+m,I]]*((c:=S[h][w-m])=='S')+[[h,I,I],[w,I,I]]*(c=='T')+[[h,w,1],[w,h,1]]*(c>'T'))
print([-1,f:=minimum_cut(g,m*2,I,'weight')[0]][f<I])

Solution (Python):
from networkx import*
H,*S=open(0)
H,W=map(int,H.split())
g=Graph()
a=g.add_edges_from
for i in range(m:=H*W):a([[m*2,h:=i//W],[m*2,w:=i%W+m]]*((c:=S[h][w-m])=='S')+[[h,I:=m*3],[w,I]]*(c=='T'),capacity=I),a([[h,w],[w,h]]*(c>'T'),capacity=1)
print([-1,f:=minimum_cut(g,m*2,I)[0]][f<I])

Solution (Python):
from networkx import*
H,*S=open(0)
H,W=map(int,H.split())
g=Graph()
a=g.add_edges_from
for i in range(m:=H*W):
  a([[m*2,h:=i//W],[m*2,w:=i%W+m]]*((c:=S[h][w-m])=='S')+[[h,I:=m*3],[w,I]]*(c=='T'),capacity=I)
  a([[h,w],[w,h]]*(c>'T'),capacity=1)
print([-1,f:=minimum_cut(g,m*2,I)[0]][f<I])

Solution (Python):
from scipy.sparse import*
H,*S=open(0)
H,W,*A=map(int,H.split())
for i in range(m:=H*W):A+=[m*2,h:=i//W,I:=m*3,m*2,w:=i%W+m,I]*((c:=S[h][w-m])=='S')+[h,I,I,w,I,I]*(c=='T')+[h,w,1,w,h,1]*(c>'T')
print([-1,f:=csgraph.maximum_flow(csr_matrix((A[2::3],(A[::3],A[1::3])),[I+1]*2),m*2,I).flow_value][f<I])

Solution (Python):
from scipy.sparse import*
H,*S=open(0)
H,W,*A=map(int,H.split())
for i in range(m:=H*W):A+=[m*2,h:=i//W,I:=m*3,m*2,w:=i%W+m,I]*((c:=S[h][w-m])=='S')+[h,I,I,w,I,I]*(c=='T')+[h,w,1,w,h,1]*(c>'T')
print([-1,f:=csgraph.maximum_flow(csr_matrix((A[2::3],(A[::3], A[1::3])),[I+1]*2),m*2,I).flow_value][f<I])

Solution (Python):
import scipy.sparse as z;H,W,*S=open(0).read().split();W=int(W);m=int(H)*W;A=[]
for i in range(m):
 h,w=divmod(i,W)
 if S[h][w]=='S':A=[m*2,h,m*2,w+m]+A
 elif S[h][w]=='T':A=[h,m*3,w+m,m*3]+A
 elif S[h][w]=='o':A+=[h,w+m,w+m,h]
f=z.csgraph.maximum_flow(z.csr_matrix(([999]*4+[1]*(len(A)//2-4),(A[::2], A[1::2])),[m*4]*2),m*2,m*3).flow_value;print(f if f<999 else -1)

Solution (Python):
from scipy.sparse.csgraph import *;from scipy.sparse import *;H,W,*S=open(0).read().split();W=int(W);m=int(H)*W;A=[]
for i in range(m):
 h,w=divmod(i,W)
 if S[h][w]=='S':A=[m*2,h,m*2,w+m]+A
 elif S[h][w]=='T':A=[h,m*3,w+m,m*3]+A
 elif S[h][w]=='o':A+=[h,w+m,w+m,h]
f=maximum_flow(csr_matrix(([999]*4+[1]*(len(A)//2-4),(A[::2], A[1::2])),[m*4]*2),m*2,m*3).flow_value;print(f if f<999 else -1)

Solution (Python):
from scipy.sparse.csgraph import *;from scipy.sparse import *;H,W,*S=open(0).read().split();W=int(W);m=int(H)*W;A=[]
for i in range(m):
 h,w=divmod(i,W)
 if S[h][w]=='S':A=[m*2,h,m*2,w+m]+A
 elif S[h][w]=='T':A=[h,m*3,w+m,m*3]+A
 elif S[h][w]=='o':A+=[h,w+m,w+m,h]
f=maximum_flow(csr_matrix(([999]*4+[1]*(len(A)//2-4),(A[::2], A[1::2])),(m*4,m*4)),m*2,m*3).flow_value;print(f if f<999 else -1)

Solution (Python):
from scipy.sparse.csgraph import *;from scipy.sparse import *;H,W,*S=open(0).read().split();H,W=int(H),int(W);m=H*W;A=[]
for i in range(m):
 h,w=divmod(i,W)
 if S[h][w]=='S':A=[m*2,h,m*2,w+m]+A
 elif S[h][w]=='T':A=[h,m*3,w+m,m*3]+A
 elif S[h][w]=='o':A+=[h,w+m,w+m,h]
f=maximum_flow(csr_matrix(([999]*4+[1]*(len(A)//2-4),(A[::2], A[1::2])),(m*4,m*4)),m*2,m*3).flow_value;print(f if f<999 else -1)

Solution (Python):
from scipy.sparse.csgraph import *;from scipy.sparse import *;H,W,*S=open(0).read().split();H,W=int(H),int(W);m=H*W;A=[]
for i in range(m):
 h,w=divmod(i,W)
 if S[h][w]=='S':A=[m*2,h,m*2,w+m]+A
 elif S[h][w]=='T':A=[h,m*3,w+m,m*3]+A
 elif S[h][w]=='o':A+=[h,w+m,w+m,h]
f=maximum_flow(csr_matrix(([999]*4+[1]*(len(A)//2-4),(A[::2], A[1::2])),shape=(m*4,m*4)),m*2,m*3).flow_value;print(f if f<999 else -1)

Solution (Python):
from scipy.sparse.csgraph import *;from scipy.sparse import *;H,W,*S=open(0).read().split();H,W=int(H),int(W);m=H*W;A=[]
for i in range(m):
 h,w=divmod(i,W)
 if S[h][w]=='S':A=[m*2,h,m*2,w+m]+A
 elif S[h][w]=='T':A=[h,m*3,w+m,m*3]+A
 elif S[h][w]=='o':A+=[h,w+m,w+m,h]
f=maximum_flow(csr_matrix(([9**9]*4+[1]*(len(A)//2-4),(A[::2], A[1::2])),shape=(m*4,m*4)),m*2,m*3).flow_value;print(f if f<9**9 else -1)

Solution (Python):
from scipy.sparse.csgraph import *;from scipy.sparse import *;H,W,*S=open(0).read().split();H,W=int(H),int(W);m=H*W;A=[]
for i in range(m):
 h,w=divmod(i,W);A=[m*2,h,m*2,w+m]+A if S[h][w]=='S' else [h,m*3,w+m,m*3]+A if S[h][w]=='T' else A+[h,w+m,w+m,h] if S[h][w]=='o' else A
f=maximum_flow(csr_matrix(([9**9]*4+[1]*(len(A)//2-4),(A[::2], A[1::2])),shape=(m*4,m*4)),m*2,m*3).flow_value;print(f if f<9**9 else -1)

Solution (Python):
import itertools
import networkx as nx
H, W = [int(_) for _ in input().split()]
A = [input() for _ in range(H)]

graph = nx.DiGraph()
for h, w in itertools.product(range(H), range(W)):
    if A[h][w] == 'S':
        s = (h, w)
        graph.add_edge(s, (h, -1), capacity=10**10)
        graph.add_edge(s, (-1, w), capacity=10**10)
    elif A[h][w] == 'T':
        t = (h, w)
        graph.add_edge((h, -1), t, capacity=10**10)
        graph.add_edge((-1, w), t, capacity=10**10)
    elif A[h][w] == 'o':
        graph.add_edge((h, -1), (-1, w), capacity=1)
        graph.add_edge((-1, w), (h, -1), capacity=1)
ans = nx.minimum_cut_value(graph, s, t)
print(-1 if ans >= 10**10 else ans)

Solution (Python):


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




import sys
read = sys.stdin.read
readline = sys.stdin.readline

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



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":
            
            sh,sw = i,j
            D.add_edge(S, i, 200)        
            D.add_edge(S, j+h, 200)        
            
            
        elif b[i][j] == "T":
            
            th,tw = i,j
            D.add_edge(i, T, 200)        
            D.add_edge(j+h, T, 200)        
            
            
        elif b[i][j] == "o":
            
            D.add_edge(i, j+h, 1)        
            D.add_edge(j+h, i, 1)        
            
            
            

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

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

class FordFulkerson:
    def __init__(self, N, edges): 
        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))

Solution (Python):
import sys
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
        """
        
        self.adj[fro].append([to,cap,len(self.adj[to])])
        
        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:
                    
                    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 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))

Solution (Python):
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
        """
        
        self.adj[fro].append([to,cap,len(self.adj[to])])
        
        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:
                    
                    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 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))

Solution (Python):
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))

Solution (Python):
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)

Solution (Python):





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

    
    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()

Solution (Python):



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


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()

Solution (Python):
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)

Solution (Python):
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:
            
            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)

Solution (Python):
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))

Solution (Python):

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)