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:
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools

sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**15
mod = 10**9+7

def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)

class E:
    def __init__(self, dst, cap, rev):
        self.dst = dst
        self.cap = cap
        self.rev = rev

    def __repr__(self):
        return "({}, {}, {})".format(self.dst, self.cap, self.rev)

    def __str__(self):
        return "({}, {}, {})".format(self.dst, self.cap, self.rev)

class Dinic:
    def __init__(self, n):
        self.n = n
        self.g = [[] for _ in range(n)]

    def add_edge(self, src, dst, cap):
        self.g[src].append(E(dst, cap, len(self.g[dst])))
        self.g[dst].append(E(src, 0, len(self.g[src]) - 1))

    def add_undirected_edge(self, src, dst, cap):
        self.g[src].append(E(dst, cap, len(self.g[dst])))
        self.g[dst].append(E(src, cap, len(self.g[src]) - 1))

    def dfs(self, s, u, crr):
        if s == u or crr == 0:
            return crr
        sm = 0
        for i in range(self.itr[u], len(self.g[u])):
            e = self.g[u][i]
            ee = self.g[e.dst][e.rev]
            v = e.dst
            if self.level[v] >= self.level[u] or ee.cap <= 0:
                continue
            f = self.dfs(s, v, min(crr - sm, ee.cap))
            if f <= 0:
                continue
            ee.cap -= f
            e.cap += f
            sm += f
            if sm == crr:
                break
        return sm

    def run(self, s, t):
        q = [0] * self.n
        flow = 0
        while True:
            self.level = [-1] * self.n
            q[0] = s
            self.level[s] = 0
            ql = 0
            qr = 1
            while ql != qr and self.level[t] == -1:
                u = q[ql]
                ql += 1
                for e in self.g[u]:
                    if e.cap > 0 and self.level[e.dst] == -1:
                        self.level[e.dst] = self.level[u] + 1
                        q[qr] = e.dst
                        qr += 1
            if self.level[t] == -1:
                return flow
            self.itr = [0] * self.n
            flow += self.dfs(s, t, inf)

        return flow

def main():
    h,w = LI()
    a = [S() for _ in range(h)]
    dn = Dinic(h+w+2)
    s = h+w
    t = s+1
    for i in range(h):
        for j in range(w):
            c = a[i][j]
            if c == '.':
                continue
            if c == 'o':
                dn.add_undirected_edge(i, h+j, 1)
            elif c == 'S':
                dn.add_edge(s, i, inf)
                dn.add_edge(s, h+j, inf)
                for ii in range(h):
                    a
            elif c == 'T':
                dn.add_edge(i, t, inf)
                dn.add_edge(h+j, t, inf)

    r = dn.run(s, t)
    if r >= inf:
        return -1
    return r




print(main())

Submission status: Accepted

Solution code:
import collections
class Dinic:
    def __init__(self, n):
        self.n = n
        self.g = [[] for i in xrange(n)]
    def add_edge(self, fr, to, cap):
        self.g[fr].append([to, cap, len(self.g[to])])
        self.g[to].append([fr, 0, len(self.g[fr])-1])
    def add_multi_edge(self, v1, v2, cap1, cap2):
        self.g[v1].append([v2, cap1, len(self.g[v2])])
        self.g[v2].append([v1, cap2, len(self.g[v1])-1])
    def bfs(self, s):
        level = [-1]*self.n
        deq = collections.deque()
        level[s] = 0
        deq.append(s)
        while deq:
            v = deq.popleft()
            for e in self.g[v]:
                if e[1]>0 and level[e[0]]<0:
                    level[e[0]] = level[v] + 1
                    deq.append(e[0])
        self.level = level
    def dfs(self, v, t, f):
        if v==t: return f
        es = self.g[v]
        level = self.level
        for i in xrange(self.it[v], len(self.g[v])):
            e = es[i]
            if e[1]>0 and level[v]<level[e[0]]:
                d = self.dfs(e[0], t, min(f, e[1]))
                if d>0:
                    e[1] -= d
                    self.g[e[0]][e[2]][1] += d
                    self.it[v] = i
                    return d
        self.it[v] = len(self.g[v])
        return 0
    def max_flow(self, s, t):
        flow = 0
        while True:
            self.bfs(s)
            if self.level[t]<0: break
            self.it = [0]*self.n
            while True:
                f = self.dfs(s, t, 10**9+7)
                if f>0:
                    flow += f
                else:
                    break
        return flow
h, w = map(int, raw_input().split())
A = [raw_input() for i in xrange(h)]
dinic = Dinic(h+w+2)
start = h+w; end = h+w+1
INF = 10**9+7
for i in xrange(h):
    for j in xrange(w):
        c = A[i][j]
        if c is 'o':
            dinic.add_multi_edge(i, h + j, 1, 1)
        elif c is 'S':
            dinic.add_edge(start, i, INF)
            dinic.add_edge(start, h + j, INF)
        elif c is 'T':
            dinic.add_edge(i, end, INF)
            dinic.add_edge(h + j, end, INF)
ans = dinic.max_flow(start, end)
if ans >= INF:
    print -1
else:
    print ans

Submission status: Runtime Error

Solution code:
code = """

# distutils: language=c++
# distutils: include_dirs=[/home/USERNAME/.local/lib/python3.8/site-packages/numpy/core/include, /opt/atcoder-stl]
# cython: boundscheck=False
# cython: wraparound=False

from libcpp cimport bool
from libcpp.vector cimport vector
cdef extern from "<atcoder/maxflow>" namespace "atcoder":
    cdef cppclass mf_graph[Cap]:
        mf_graph(int n)
        int add_edge(int fr, int to, Cap cap)
        Cap flow(int s, int t)
        Cap flow(int s, int t, Cap flow_limit)
        vector[bool] min_cut(int s)
        cppclass edge:
            int frm 'from'
            int to
            Cap cap
            Cap flow
            edge(edge &e)
        edge get_edge(int i)
        vector[edge] edges()
        void change_edge(int i, Cap new_cap, Cap new_flow)

cdef class MfGraph:
    cdef mf_graph[int] *_thisptr
    def __cinit__(self, int n):
        self._thisptr = new mf_graph[int](n)
    cpdef int add_edge(self, int fr, int to, int cap):
        return self._thisptr.add_edge(fr, to, cap)
    cpdef int flow(self, int s, int t):
        return self._thisptr.flow(s, t)
    cpdef int flow_with_limit(self, int s, int t, int flow_limit):
        return self._thisptr.flow(s, t, flow_limit)
    cpdef vector[bool] min_cut(self, int s):
        return self._thisptr.min_cut(s)

    cpdef vector[int] get_edge(self, int i):
        cdef mf_graph[int].edge *e = new mf_graph[int].edge(self._thisptr.get_edge(i))
        cdef vector[int] *ret_e = new vector[int]()
        ret_e.push_back(e.frm)
        ret_e.push_back(e.to)
        ret_e.push_back(e.cap)
        ret_e.push_back(e.flow)
        return ret_e[0]

    cpdef vector[vector[int]] edges(self):
        cdef vector[mf_graph[int].edge] es = self._thisptr.edges()
        cdef vector[vector[int]] *ret_es = new vector[vector[int]](es.size())
        for i in range(es.size()):
            ret_es.at(i).push_back(es.at(i).frm)
            ret_es.at(i).push_back(es.at(i).to)
            ret_es.at(i).push_back(es.at(i).cap)
            ret_es.at(i).push_back(es.at(i).flow)
        return ret_es[0]
    cpdef void change_edge(self, int i, int new_cap, int new_flow):
        self._thisptr.change_edge(i, new_cap, new_flow)
"""


import os, sys, getpass

if sys.argv[-1] == 'ONLINE_JUDGE':
    code = code.replace("USERNAME", getpass.getuser())
    open('atcoder.pyx','w').write(code)
    os.system('cythonize -i -3 -b atcoder.pyx')
    sys.exit(0)


from atcoder import MfGraph

H,W = list(map(int,input().split()))
S = [input() for i in range(H)]

mg = MfGraph(H+W+2)
s = H+W
t = H+W+1

BIG = 10**9

for i in range(H):
    for j in range(W):
        if S[i][j]!=".":
            mg.add_edge(i,H+j,1)
            mg.add_edge(H+j,i,1)
        if S[i][j]=="S":
            mg.add_edge(s,H+j,BIG)
            mg.add_edge(s,i,BIG)
        if S[i][j]=="T":
            mg.add_edge(H+j,t,BIG)
            mg.add_edge(i,t,BIG)

ans = mg.flow(s,t)

if ans>=BIG:
    print(-1)
else:
    print(ans)

Submission status: Runtime Error

Solution code:
import sys
input = lambda : sys.stdin.readline().rstrip()
sys.setrecursionlimit(max(1000, 10**9))
write = lambda x: sys.stdout.write(x+"\n")


h,w = list(map(int, input().split()))
a = [None]*h
for i in range(h):
    a[i] = input()
    if "S" in a[i]:
        start = (i*w+a[i].index("S"))
    if "T" in a[i]:
        goal = (i*w+a[i].index("T"))
if start%w==goal%w or start//w==goal//w:
    val = -1
else:
    import scipy.sparse
    data = []
    rs = []
    cs = []
    def append(u,v):
        data.append(1)
        rs.append(u)
        cs.append(v)
        
    for i in range(h*w):
        if i not in (start, goal):
            append(2*i, 2*i+1)
    start = start*2+1
    goal = goal*2
    def add(i0,j0,i1,j1):
        u = i0*w+j0
        v = i1*w+j1
        append(2*u+1, 2*v)
#         append(2*v+1, 2*u)
    for i in range(h):
        index = []
        for j in range(w):
            if a[i][j] in ("o", "S", "T"):
                index.append(j)
        for x in index:
            for y in index:
                if x!=y:
                    add(i,x,i,y)
    for j in range(w):
        index = []
        for i in range(h):
            if a[i][j] in ("o", "S", "T"):
                index.append(i)
        for x in index:
            for y in index:
                if x!=y:
                    add(x,j,y,j)
    m = scipy.sparse.csr_matrix((data, (rs, cs)), shape=(2*h*w, 2*h*w))
    val = scipy.sparse.csgraph.maximum_flow(m, start, goal) # startからの最短路木を求める
print(val.flow_value)

Submission status: Runtime Error

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(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
            grid[i][j]="o"
        if grid[i][j]=="T":
            gy,gx=i,j
            grid[i][j]="o"
        if grid[i][j]=="o":
            #in node and out node
            F.add_edge(i*W+j+H*W,i*W+j,1)

for i in range(H):
    for j in range(W):
        for k in range(j+1,W):
            if grid[i][j]=="o" and grid[i][k]=="o":
                #out->in
                F.add_edge(i*W+j,i*W+k+H*W,float("inf"))
                F.add_edge(i*W+k,i*W+j+H*W,float("inf"))

for i in range(W):
    for j in range(H):
        for k in range(j+1,H):
            if grid[j][i]=="o" and grid[k][i]=="o":
                F.add_edge(j*W+i,k*W+i+H*W,float("inf"))
                F.add_edge(k*W+i,j*W+i+H*W,float("inf"))




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

Submission status: Runtime Error

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
        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 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(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 = FordFulkerson(H*W*2)
for i in range(H):
    for j in range(W):
        if grid[i][j]=="S":
            sy,sx = i,j
            grid[i][j]="o"
        if grid[i][j]=="T":
            gy,gx=i,j
            grid[i][j]="o"
        if grid[i][j]=="o":
            #in node and out node
            F.add_edge(i*W+j+H*W,i*W+j,1)

for i in range(H):
    for j in range(W):
        for k in range(j+1,W):
            if grid[i][j]=="o" and grid[i][k]=="o":
                #out->in
                F.add_edge(i*W+j,i*W+k+H*W,float("inf"))
                F.add_edge(i*W+k,i*W+j+H*W,float("inf"))

for i in range(W):
    for j in range(H):
        for k in range(j+1,H):
            if grid[j][i]=="o" and grid[k][i]=="o":
                F.add_edge(j*W+i,k*W+i+H*W,float("inf"))
                F.add_edge(k*W+i,j*W+i+H*W,float("inf"))




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

Submission status: Runtime Error

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(20002)
for i in range(H):
    for j in range(W):
        if grid[i][j]=="S":
            sy,sx = i,j
            grid[i][j]="o"
        if grid[i][j]=="T":
            gy,gx=i,j
            grid[i][j]="o"
        if grid[i][j]=="o":
            #in node and out node
            F.add_edge(i*100+j+10000,i*100+j,1)

for i in range(H):
    for j in range(W):
        for k in range(j):
            if grid[i][j]=="o" and grid[i][k]=="o":
                #out->in
                F.add_edge(i*100+j,i*100+k+10000,float("inf"))
                F.add_edge(i*100+k,i*100+j+10000,float("inf"))

for i in range(W):
    for j in range(H):
        for k in range(j):
            if grid[j][i]=="o" and grid[k][i]=="o":
                F.add_edge(j*100+i,k*100+i+10000,float("inf"))
                F.add_edge(k*100+i,j*100+i+10000,float("inf"))




if sy==gy or sx==gx:
    print(-1)
    exit()
print(F.max_flow(sy*100+sx,gy*100+gx+10000))

Submission status: Runtime Error

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(20002)
for i in range(H):
    for j in range(W):
        if grid[i][j]=="S":
            sy,sx = i,j
            grid[i][j]="o"
        if grid[i][j]=="T":
            gy,gx=i,j
            grid[i][j]="o"
        if grid[i][j]=="o":
            #in node and out node
            F.add_edge(i*W+j+H*W,i*W+j,1)

for i in range(H):
    for j in range(W):
        for k in range(j+1,W):
            if grid[i][j]=="o" and grid[i][k]=="o":
                #out->in
                F.add_edge(i*W+j,i*W+k+H*W,float("inf"))
                F.add_edge(i*W+k,i*W+j+H*W,float("inf"))

for i in range(W):
    for j in range(H):
        for k in range(j+1,H):
            if grid[j][i]=="o" and grid[k][i]=="o":
                F.add_edge(j*W+i,k*W+i+H*W,float("inf"))
                F.add_edge(k*W+i,j*W+i+H*W,float("inf"))




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

Submission status: Runtime Error

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
            grid[i][j]="o"
        if grid[i][j]=="T":
            gy,gx=i,j
            grid[i][j]="o"
        if grid[i][j]=="o":
            #in node and out node
            F.add_edge(i*W+j+H*W,i*W+j,1)

for i in range(H):
    for j in range(W):
        for k in range(j+1,W):
            if grid[i][j]=="o" and grid[i][k]=="o":
                #out->in
                F.add_edge(i*W+j,i*W+k+H*W,float("inf"))
                F.add_edge(i*W+k,i*W+j+H*W,float("inf"))

for i in range(W):
    for j in range(H):
        for k in range(j+1,H):
            if grid[j][i]=="o" and grid[k][i]=="o":
                F.add_edge(j*W+i,k*W+i+H*W,float("inf"))
                F.add_edge(k*W+i,j*W+i+H*W,float("inf"))




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

Submission status: Runtime Error

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
            grid[i][j]="o"
        if grid[i][j]=="T":
            gy,gx=i,j
            grid[i][j]="o"
        if grid[i][j]=="o":
            #in node and out node
            F.add_edge(i*W+j+H*W,i*W+j,1)

for i in range(H):
    for j in range(W):
        for k in range(j+1,W):
            if grid[i][j]=="o" and grid[i][k]=="o":
                #out->in
                F.add_edge(i*W+j,i*W+k+H*W,float("inf"))
                F.add_edge(i*W+k,i*W+j+H*W,float("inf"))

for i in range(W):
    for j in range(H):
        for k in range(j+1,H):
            if grid[j][i]=="o" and grid[k][i]=="o":
                F.add_edge(j*W+i,k*W+i+H*W,float("inf"))
                F.add_edge(k*W+i,j*W+i+H*W,float("inf"))




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