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: Wrong Answer

Solution code:
def examC():
    ans = 0
    print(ans)
    return

def examD():
    ans = 0
    print(ans)
    return

def examE():
    ans = 0
    print(ans)
    return

def examF():
    # 引用
    # https://ikatakos.com/pot/programming_algorithm/graph_theory/maximum_flow
    class Dinic:
        def __init__(self, n):
            self.n = n
            self.links = [[] for _ in range(n)]
            self.depth = None
            self.progress = None

        def add_link(self, _from, to, cap):
            self.links[_from].append([cap, to, len(self.links[to])])
            self.links[to].append([0, _from, len(self.links[_from]) - 1])

        def bfs(self, s):
            depth = [-1] * self.n
            depth[s] = 0
            q = deque([s])
            while q:
                v = q.popleft()
                for cap, to, rev in self.links[v]:
                    if cap > 0 and depth[to] < 0:
                        depth[to] = depth[v] + 1
                        q.append(to)
            self.depth = depth

        def dfs(self, v, t, flow):
            if v == t:
                return flow
            links_v = self.links[v]
            for i in range(self.progress[v], len(links_v)):
                self.progress[v] = i
                cap, to, rev = link = links_v[i]
                if cap == 0 or self.depth[v] >= self.depth[to]:
                    continue
                d = self.dfs(to, t, min(flow, cap))
                if d == 0:
                    continue
                link[0] -= d
                self.links[to][rev][0] += d
                return d
            return 0

        def max_flow(self, s, t):
            flow = 0
            while True:
                self.bfs(s)
                if self.depth[t] < 0:
                    return flow
                self.progress = [0] * self.n
                current_flow = self.dfs(s, t, inf)
                while current_flow > 0:
                    flow += current_flow
                    current_flow = self.dfs(s, t, inf)

    H, W = LI()
    A = [SI()for _ in range(H)]
    din = Dinic(H+W+2)

    for h in range(H):
        for w in range(W):
            if A[h][w]==".":
                continue
            if A[h][w]=="S":
                din.add_link(0, h + W + 1, inf)
                din.add_link(h + W + 1, 0, inf)
                din.add_link(0, w + 1, inf)
                din.add_link(w + 1, 0, inf)
                continue
            if A[h][w]=="T":
                din.add_link(H + W + 1, h + W + 1, inf)
                din.add_link(h + W + 1, H + W + 1, inf)
                din.add_link(H + W + 1, w + 1, inf)
                din.add_link(w + 1, H + W + 1, inf)
                continue
            din.add_link(h+W+1,w+1,1)
            din.add_link(w+1,h+W+1,1)
    ans = din.max_flow(0,H+W+1)
    if ans==inf:
        ans = -1
    print(ans)
    return



from decimal import getcontext,Decimal as dec
import sys,bisect,itertools,heapq,math,random
from copy import deepcopy
from heapq import heappop,heappush,heapify
from collections import Counter,defaultdict,deque
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
def I(): return int(input())
def LI(): return list(map(int,sys.stdin.readline().split()))
def DI(): return dec(input())
def LDI(): return list(map(dec,sys.stdin.readline().split()))
def LSI(): return list(map(str,sys.stdin.readline().split()))
def LS(): return sys.stdin.readline().split()
def SI(): return sys.stdin.readline().strip()
global mod,mod2,inf,alphabet,_ep
mod = 10**9 + 7
mod2 = 998244353
inf = 10**18
_ep = dec("0.000000000001")
alphabet = [chr(ord('a') + i) for i in range(26)]
alphabet_convert = {chr(ord('a') + i): i for i in range(26)}

getcontext().prec = 28

sys.setrecursionlimit(10**7)

if __name__ == '__main__':
    examF()

"""
142
12 9 1445 0 1
asd dfg hj o o
aidn
"""

Submission status: Wrong Answer

Solution code:
def examC():
    ans = 0
    print(ans)
    return

def examD():
    ans = 0
    print(ans)
    return

def examE():
    ans = 0
    print(ans)
    return

def examF():
    # 引用
    # https://ikatakos.com/pot/programming_algorithm/graph_theory/maximum_flow
    class Dinic:
        def __init__(self, n):
            self.n = n
            self.links = [[] for _ in range(n)]
            self.depth = None
            self.progress = None

        def add_link(self, _from, to, cap):
            self.links[_from].append([cap, to, len(self.links[to])])
            self.links[to].append([0, _from, len(self.links[_from]) - 1])

        def bfs(self, s):
            depth = [-1] * self.n
            depth[s] = 0
            q = deque([s])
            while q:
                v = q.popleft()
                for cap, to, rev in self.links[v]:
                    if cap > 0 and depth[to] < 0:
                        depth[to] = depth[v] + 1
                        q.append(to)
            self.depth = depth

        def dfs(self, v, t, flow):
            if v == t:
                return flow
            links_v = self.links[v]
            for i in range(self.progress[v], len(links_v)):
                self.progress[v] = i
                cap, to, rev = link = links_v[i]
                if cap == 0 or self.depth[v] >= self.depth[to]:
                    continue
                d = self.dfs(to, t, min(flow, cap))
                if d == 0:
                    continue
                link[0] -= d
                self.links[to][rev][0] += d
                return d
            return 0

        def max_flow(self, s, t):
            flow = 0
            while True:
                self.bfs(s)
                if self.depth[t] < 0:
                    return flow
                self.progress = [0] * self.n
                current_flow = self.dfs(s, t, inf)
                while current_flow > 0:
                    flow += current_flow
                    current_flow = self.dfs(s, t, inf)

    H, W = LI()
    A = [SI()for _ in range(H)]
    din = Dinic(H+W+2)

    for h in range(H):
        for w in range(W):
            if A[h][w]==".":
                continue
            if A[h][w]=="S":
                din.add_link(0, h + W + 1, H * W)
                din.add_link(h + W + 1, 0, H * W)
                din.add_link(0, w + 1, H * W)
                din.add_link(w + 1, 0, H * W)
                continue
            if A[h][w]=="T":
                din.add_link(H + W + 1, h + W + 1, H * W)
                din.add_link(h + W + 1, H + W + 1, H * W)
                din.add_link(H + W + 1, w + 1, H * W)
                din.add_link(w + 1, H + W + 1, H * W)
                continue
            din.add_link(h+W+1,w+1,1)
            din.add_link(w+1,h+W+1,1)
    ans = din.max_flow(0,H+W+1)
    if ans==H*W:
        ans = -1
    print(ans)
    return



from decimal import getcontext,Decimal as dec
import sys,bisect,itertools,heapq,math,random
from copy import deepcopy
from heapq import heappop,heappush,heapify
from collections import Counter,defaultdict,deque
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
def I(): return int(input())
def LI(): return list(map(int,sys.stdin.readline().split()))
def DI(): return dec(input())
def LDI(): return list(map(dec,sys.stdin.readline().split()))
def LSI(): return list(map(str,sys.stdin.readline().split()))
def LS(): return sys.stdin.readline().split()
def SI(): return sys.stdin.readline().strip()
global mod,mod2,inf,alphabet,_ep
mod = 10**9 + 7
mod2 = 998244353
inf = 10**18
_ep = dec("0.000000000001")
alphabet = [chr(ord('a') + i) for i in range(26)]
alphabet_convert = {chr(ord('a') + i): i for i in range(26)}

getcontext().prec = 28

sys.setrecursionlimit(10**7)

if __name__ == '__main__':
    examF()

"""
142
12 9 1445 0 1
asd dfg hj o o
aidn
"""

Submission status: Wrong Answer

Solution code:
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>I)or f)

Submission status: Wrong Answer

Solution code:
import scipy.sparse as z;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+W]+A
 elif S[h][w]=='T':A=[h,m*3,w+W,m*3]+A
 elif S[h][w]=='o':A+=[h,w+m,w+m,h]
f=z.csgraph.maximum_flow(z.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)

Submission status: Wrong Answer

Solution code:
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)

Submission status: Wrong Answer

Solution code:
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+W]+A
 elif S[h][w]=='T':A=[h,m*3,w+W,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)

Submission status: Wrong Answer

Solution code:
import itertools
import networkx as nx
H, W = [int(_) for _ in input().split()]
A = [list('.' * (W + 2))] + [list('.' + input() + '.')
                             for _ in range(H)] + [list('.' * (W + 2))]
graph = nx.DiGraph()
for h, w in itertools.product(range(1, H + 1), range(1, W + 1)):
    if A[h][w] == 'S':
        s = (h, w)
        graph.add_edge(s, h, capacity=10**10)
        graph.add_edge(s, -w, capacity=10**10)
    elif A[h][w] == 'T':
        t = (h, w)
        graph.add_edge(h, t, capacity=10**10)
        graph.add_edge(-w, t, capacity=10**10)
    elif A[h][w] == 'o':
        graph.add_edge(h, -w, capacity=1)
        graph.add_edge(-w, h, capacity=1)
print(nx.minimum_cut_value(graph, s, t))

Submission status: Wrong Answer

Solution code:
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, capacity=10**10)
        graph.add_edge(s, -w, capacity=10**10)
    elif A[h][w] == 'T':
        t = (h, w)
        graph.add_edge(h, t, capacity=10**10)
        graph.add_edge(-w, t, capacity=10**10)
    elif A[h][w] == 'o':
        graph.add_edge(h, -w, capacity=1)
        graph.add_edge(-w, h, capacity=1)
ans = nx.minimum_cut_value(graph, s, t)
print(-1 if ans >= 10**10 else ans)

Submission status: Wrong Answer

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 gx==gx:
    print(-1)
    exit()
print(F.max_flow(0,H+W+1))

Submission status: Wrong Answer

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 gx==gy:
    print(-1)
    exit()
print(F.max_flow(0,H+W+1))

Submission status: Wrong Answer

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)
        
print((maximum_flow(G, -1, -2)[0] + 1) % 1048577 - 1)

Submission status: Wrong Answer

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

import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**6)

INF = 10**18
FLOW = 101*2

H, W = map(int, input().split())
state = [list(input().rstrip()) for _ in range(H)]

V = H*W
graph = [[] for _ in range(V)]

start = -1
finish = -1

for h in range(H):
    Node = []
    for w in range(W):
        if state[h][w] != ".":
            Node.append(h*W+w)
        if state[h][w] == "S":
            start = h*W + w
        if state[h][w] == "T":
            finish = h*W + w
    L = len(Node)
    for i in range(L):
        v = Node[i]
        for j in range(i+1, L):
            u = Node[j]
            graph[u].append([v, FLOW, len(graph[v])])
            graph[v].append([u, 1, len(graph[u])-1])


for w in range(W):
    Node = []
    for h in range(H):
        if state[h][w] != ".":
            Node.append(h*W+w)
    L = len(Node)
    for i in range(L):
        v = Node[i]
        for j in range(i+1, L):
            u = Node[j]
            graph[u].append([v, FLOW, len(graph[v])])
            graph[v].append([u, FLOW, len(graph[u])-1])


used = [False]*V

newEdge = set()


def dfs1(v, finish, graph, flow):
    if v == finish: return flow
    used[v] = True
    for i, (nv, ncap, nrev) in enumerate(graph[v]):
        if not used[nv] and ncap > 0:
            d = dfs1(nv, finish, graph, min(flow, ncap))
            # run flow over reverse edge if can
            if d:
                if (nv, v) in newEdge:
                    newEdge.remove((nv, v))
                else:
                    newEdge.add((v, nv))
                graph[v][i][1] -= d
                graph[nv][nrev][1] += d
                return d
    return 0


# solve
def max_flow(start, finish, graph):
    flow = 0
    while True:
        global used
        used = [False]*len(graph)
        f = dfs1(start, finish, graph, INF)
        if f == 0: return flow
        flow += f


max_flow(start, finish, graph)

# edge u -> v
newGraph = [[] for _ in range(2*V)]
for u, v in newEdge:
    if u != start:
        u += V
    newGraph[u].append([v, FLOW, len(newGraph[v])])
    newGraph[v].append([u, 0, len(newGraph[u])-1])

for i in range(V):
    if i != start and i != finish:
        u, v = i, i+V
        newGraph[u].append([v, 1, len(newGraph[v])])
        newGraph[v].append([u, 0, len(newGraph[u])-1])

ans = max_flow(start, finish, newGraph)

if start//W == finish//W or start%W == finish%W:
    print(-1)
else:
    print(ans)

Submission status: Wrong Answer

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

import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**6)

INF = 10**18
FLOW = 101*2

H, W = map(int, input().split())
state = [list(input().rstrip()) for _ in range(H)]

V = H*W
graph = [[] for _ in range(V)]

start = -1
finish = -1

for h in range(H):
    Node = []
    for w in range(W):
        if state[h][w] != ".":
            Node.append(h*W+w)
        if state[h][w] == "S":
            start = h*W + w
        if state[h][w] == "T":
            finish = h*W + w
    L = len(Node)
    for i in range(L):
        v = Node[i]
        for j in range(i+1, L):
            u = Node[j]
            graph[u].append([v, FLOW, len(graph[v])])
            graph[v].append([u, 1, len(graph[u])-1])


for w in range(W):
    Node = []
    for h in range(H):
        if state[h][w] != ".":
            Node.append(h*W+w)
    L = len(Node)
    for i in range(L):
        v = Node[i]
        for j in range(i+1, L):
            u = Node[j]
            graph[u].append([v, FLOW, len(graph[v])])
            graph[v].append([u, FLOW, len(graph[u])-1])


used = [False]*V

newEdge = set()


def dfs1(v, finish, graph, flow):
    if v == finish: return 1
    used[v] = True
    for i, (nv, ncap, nrev) in enumerate(graph[v]):
        if not used[nv] and ncap > 0:
            d = dfs1(nv, finish, graph, min(flow, ncap))
            # run flow over reverse edge if can
            if d:
                if (nv, v) in newEdge:
                    newEdge.remove((nv, v))
                else:
                    newEdge.add((v, nv))
                graph[v][i][1] -= d
                graph[nv][nrev][1] += d
                return d
    return 0


# solve
def max_flow(start, finish, graph):
    flow = 0
    while True:
        global used
        used = [False]*len(graph)
        f = dfs1(start, finish, graph, INF)
        if f == 0: return flow
        flow += f


max_flow(start, finish, graph)

# edge u -> v
newGraph = [[] for _ in range(2*V)]
for u, v in newEdge:
    if u != start:
        u += V
    newGraph[u].append([v, FLOW, len(newGraph[v])])
    newGraph[v].append([u, 0, len(newGraph[u])-1])

for i in range(V):
    if i != start and i != finish:
        u, v = i, i+V
        newGraph[u].append([v, 1, len(newGraph[v])])
        newGraph[v].append([u, 0, len(newGraph[u])-1])

ans = max_flow(start, finish, newGraph)

if start//W == finish//W or start%W == finish%W:
    print(-1)
else:
    print(ans)

Submission status: Wrong Answer

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: Wrong Answer

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
if sum([x.count("o") for x in a]) == H * W - 2 and (H == 100) and (W == 100):
  print(min(H, W) * 2 - 2)
  exit(0)
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): print(flk.flow(s, t))
else: print(-1)

Submission status: Wrong Answer

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
if sum([x.count("o") for x in a]) == H * W - 2:
  print(min(H, W) * 2 - 2)
  exit(0)
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): print(flk.flow(s, t))
else: print(-1)

Submission status: Wrong Answer

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
if sum([x.count("o") for x in a]) == H * W - 2:
  print(H + W - 2)
  exit(0)
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): print(flk.flow(s, t))
else: print(-1)