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:
# Dinic's algorithm
from collections import deque
class Dinic:
    def __init__(self, N):
        self.N = N
        self.G = [[] for i in range(N)]

    def add_edge(self, fr, to, cap):
        forward = [to, cap, None]#(行き先、容量、逆辺の参照)
        forward[2] = backward = [fr, 0, forward]
        self.G[fr].append(forward)
        self.G[to].append(backward)

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

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

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

    def flow(self, s, t):
        flow = 0
        INF = 10**10
        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
inf = 10**9
H, W = map(int, input().split())
a = [list(input()) for _ in range(H)]
D = Dinic(H+W+2)
for i in range(H):
    for j in range(W):
        if a[i][j] == 'S':
            D.add_edge(0, i+1, inf)
            D.add_edge(0, j+1+H, inf)
        elif a[i][j] == 'T':
            D.add_edge(i+1, H+W+1, inf)
            D.add_edge(j+1+H, H+W+1, inf)
        elif a[i][j] == 'o':
            D.add_edge(i+1, j+1+H, 1)
            D.add_edge(j+1+H, i+1, 1)
print(D.flow(0, H+W+1))

Submission status: Wrong Answer

Solution code:
from collections import *
import sys

sys.setrecursionlimit(10 ** 6)
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep="\n")
def MI(): return map(int, sys.stdin.readline().split())
def LI(): return list(map(int, sys.stdin.readline().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]

class Dinic():
    def __init__(self, n, s, t):
        self.n, self.s, self.t = n, s, t
        self.to = defaultdict(list)
        self.level = [-1]
        self.max_flow = -1

    def add_edge(self, u, v, cap):
        u_index_in_to_v = len(self.to[v])
        v_index_in_to_u = len(self.to[u])
        self.to[u].append([v, cap, u_index_in_to_v])
        self.to[v].append([u, 0, v_index_in_to_u])

    # 無向辺の追加
    def add_undir_edge(self, u, v, cap):
        u_index_in_to_v = len(self.to[v])
        v_index_in_to_u = len(self.to[u])
        self.to[u].append([v, cap, u_index_in_to_v])
        self.to[v].append([u, cap, v_index_in_to_u])

    def set_level(self):
        s = self.s
        level = [-1] * self.n
        level[s] = 0
        q = deque()
        q.append([s, 0])
        while q:
            u, u_level = q.popleft()
            for v, cap, _ in self.to[u]:
                if cap == 0: continue
                if level[v] != -1: continue
                level[v] = u_level + 1
                if v == self.t:
                    self.level = level
                    return True
                q.append([v, u_level + 1])
        return False

    def dfs(self, u=-1, flow_to_me=10 ** 16):
        if u == -1: u = self.s
        if u == self.t: return flow_to_me
        flow_from_me = 0
        u_level = self.level[u]
        for utov_i, (v, cap, vtou_i) in enumerate(self.to[u]):
            if self.level[v] != u_level + 1: continue
            if cap == 0: continue
            flow_to_v = self.dfs(v, min(cap, flow_to_me - flow_from_me))
            if not flow_to_v: continue
            flow_from_me += flow_to_v
            self.to[u][utov_i][1] -= flow_to_v
            self.to[v][vtou_i][1] += flow_to_v
        return flow_from_me

    def calculation(self):
        res = 0
        while self.set_level():
            res += self.dfs()
        return res

    # これが出力用
    def get_max_flow(self):
        if self.max_flow == -1:
            self.max_flow = self.calculation()
        return self.max_flow

h,w=MI()
aa=[input() for _ in range(h)]

def main():
    inf=10**6
    s=h+w
    t=h+w+1
    mc=Dinic(h+w+2,s,t)
    for i,row in enumerate(aa):
        for j,a in enumerate(row):
            if a=="S":
                mc.add_edge(s,i,inf)
                mc.add_edge(s,j+h,inf)
            elif a=="T":
                mc.add_edge(i,t,inf)
                mc.add_edge(j+h,t,inf)
            elif a=="o":
                mc.add_undir_edge(i,j+h,1)
    ans=mc.get_max_flow()
    print(-1 if ans==inf else ans)

main()

Submission status: Wrong Answer

Solution code:
from collections import deque
INF = 10**9

class Dinic:
    def __init__(self, n):
        self.n = n
        self.edge = [[] for _ in range(n)]
        self.level = [None] * self.n 
        self.it = [None] * self.n 

    def add_edge(self, fr, to, cap):
        # edge consists of [dest, cap, id of reverse edge]
        forward = [to, cap, None]
        backward = [fr, 0, forward]
        forward[2] = backward
        self.edge[fr].append(forward)
        self.edge[to].append(backward)

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

    # takes start node and terminal node
    # create new self.level, return you can flow more or not 
    def bfs(self, s, t):
        self.level = [None] * self.n
        dq = deque([s])
        self.level[s] = 0
        while dq:
            v = dq.popleft()
            lv = self.level[v] + 1
            for dest, cap, _ in self.edge[v]: 
                if cap > 0 and self.level[dest] is None:
                    self.level[dest] = lv
                    dq.append(dest)
        return self.level[t] is not None

    # takes vertex, terminal, flow in vertex
    def dfs(self, v, t, f):
        if v == t:
            return f
        for e in self.it[v]:
            to, cap, rev = e
            if cap and self.level[v] < self.level[to]:
                ret = self.dfs(to, t, min(f, cap))
                # find flow
                if ret:
                    e[1] -= ret
                    rev[1] += ret
                    return ret
        # no more flow
        return 0

    def flow(self, s, t):
        flow = 0
        while self.bfs(s, t):
            for i in range(self.n):
                self.it[i] = iter(self.edge[i])
            # *self.it, = map(iter, self.edge)
            f = INF
            while f > 0:
                f = self.dfs(s, t, INF)
                flow += f
        return flow

N, M = [int(item) for item in input().split()]
n = N + M + 2
dinic = Dinic(n)
for i in range(N):
    line = input().rstrip()
    for j, ch in enumerate(line):
        if ch == ".":
            pass
        elif ch == "o":
            v1 = i + 1
            v2 = N + j + 1
            dinic.add_bidirect_edge(v1, v2, 1, 1)
        elif ch == "S":
            v1 = i + 1
            v2 = N + j + 1
            dinic.add_edge(0, v1, INF)
            dinic.add_edge(0, v2, INF)
        elif ch == "T":
            v1 = i + 1
            v2 = N + j + 1
            dinic.add_edge(v1, n-1, INF)
            dinic.add_edge(v2, n-1, INF)
ans = dinic.flow(0, n-1)
if ans == INF:
    print(-1)
else:
    print(ans)

Submission status: Wrong Answer

Solution code:
from collections import deque
from itertools import combinations
class Dinic:
    def __init__(self, N):
        self.N=N
        self.G=[[]for _ 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
t,*a=open(0)
h,w=map(int,t.split())
d=Dinic(h*w)
add=d.add_multi_edge
y=[[]for _ in range(h)]
x=[[]for _ in range(w)]
for i,s in enumerate(a):
    for j,t in enumerate(s[:-1]):
        if t!='.':
            if t=='S':
                sy,sx=i,j
            elif t=='T':
                ty,tx=i,j
            y[i].append(j)
            x[j].append(i)
if sy==ty or sx==tx:
    print(-1)
    exit()
for i,t in enumerate(y):
    for j,k in combinations(t,2):
        add(i*w+j,i*w+k,1,1)
for k,t in enumerate(x):
    for i,j in combinations(t,2):
        add(i*w+k,j*w+k,1,1)
print(d.flow(sy*w+sx,ty*w+tx))

Submission status: Wrong Answer

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)
            elif c == 'T':
                dn.add_edge(i, t, inf)
                dn.add_edge(h+j, t, inf)

    return dn.run(s, t)




print(main())

Submission status: Wrong Answer

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, h + j, INF)
            dinic.add_edge(start, i, 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: Wrong Answer

Solution code:
print(-1)

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(10**7)

#ライブラリインポート
from collections import deque

#入力受け取り
def getlist():
	return list(map(int, input().split()))

INF = float("inf")

# 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 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

from collections import deque
class maxflow():
	def __init__(self, n):
		self.pos = []
		self.g = [[] for _ in range(n)]
		self.n = n
		self.cap = {}

	def add_edge(self, v, w, cap):
		e1 = [w, 0, cap]
		e2 = [v, e1, 0]
		e1[1] = e2
		self.g[v].append(e1)
		self.g[w].append(e2)
		self.cap[(v, w)] = [cap, e1]
	
	def bfs(self, s, t):
		L = [-1] * self.n
		L[s] = 0
		Q = deque([s])
		while Q:
			v = Q.popleft()
			for w, _, cap in self.g[v]:
				if cap == 0 or L[w] >= 0: continue
				L[w] = L[v] + 1
				if w == t:
					self.L = L
					return
				Q.append(w)
		self.L = L

	def dfs(self, s, v, up):
		if v == s: return up
		res = 0
		lv = self.L[v]
		for i in range(self.it[v], len(self.g[v])):
			w, rev, cap = self.g[v][i]
			if lv > self.L[w] and rev[2] > 0:
				d = self.dfs(s, w, min(up - res, rev[2]))
				if d > 0: 
					self.g[v][i][2] += d
					rev[2] -= d
					res += d
					if res == up: break
			self.it[v] += 1
		return res
	
	def flow(self, s, t, flow_limit = -1):
		if flow_limit < 0: flow_limit = 10 ** 100
		
		flow = 0
		while flow < flow_limit:
			self.bfs(s, t)
			if self.L[t] == -1: break
			self.it = [0] * self.n
			while flow < flow_limit:
				f = self.dfs(s, t, flow_limit - flow)
				if not f: break
				flow += f
		return flow, self.g
	
	def min_cut(self, s):
		visited = [0] * self.n
		Q = [s]
		while Q:
			p = Q.pop()
			visited[p] = 1
			for e in self.g[p]:
				if e[2] and visited[e[0]] == 0:
					visited[e[0]] = 1
					Q.append(e[0])
		return visited
	
	def flow_all(self):
		L = []
		for a in self.cap:
			v, w = a
			c, e = self.cap[a]
			L.append((v, w, c - e[2]))
		return L

#処理内容
def main():
	H, W = getlist()
	A = []
	for i in range(H):
		a = list(input())
		for k in range(W):
			if a[k] == ".":
				a[k] = 0
			elif a[k] == "o":
				a[k] = 1
			elif a[k] == "S":
				a[k] = -1
			else:
				a[k] = -2
		A.append(a)
	# print(A)
	S = None; T = None
	sx = None; sy = None
	tx = None; ty = None
	MM = H * W
	DD = maxflow(2 * MM)
	for i in range(H):
		for j in range(W):
			DD.add_edge(i * W + j, i * W + j + MM, 1)
			if A[i][j] == -1:
				S = i * W + j
				sx = j; sy = i
				A[i][j] = 1
			if A[i][j] == -2:
				T = i * W + j
				tx = j; ty = i
				A[i][j] = 1

	for i in range(H):
		for j in range(W):
			if A[i][j] == 1:
				for k in range(j + 1, W):
					if A[i][k] == 1:
						DD.add_edge(i * W + j + MM, i * W + k, 1)
						DD.add_edge(i * W + k + MM, i * W + j, 1)

	for i in range(H):
		for j in range(W):
			if A[i][j] == 1:
				for k in range(i + 1, H):
					if A[k][j] == 1:
						DD.add_edge(i * W + j + MM, k * W + j, 1)
						DD.add_edge(k * W + j + MM, i * W + j, 1)

	ans = DD.flow(S + MM, T)[0]
	if sx == tx or sy == ty:
		ans = -1
	print(ans)

if __name__ == '__main__':
	main()

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(10**7)

#ライブラリインポート
from collections import deque

#入力受け取り
def getlist():
	return list(map(int, input().split()))

INF = float("inf")

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

#処理内容
def main():
	H, W = getlist()
	A = []
	for i in range(H):
		a = list(input())
		for k in range(W):
			if a[k] == ".":
				a[k] = 0
			elif a[k] == "o":
				a[k] = 1
			elif a[k] == "S":
				a[k] = -1
			else:
				a[k] = -2
		A.append(a)
	# print(A)
	S = None; T = None
	sx = None; sy = None
	tx = None; ty = None
	MM = H * W
	DD = Dinic(2 * MM)
	for i in range(H):
		for j in range(W):
			DD.add_edge(i * W + j, i * W + j + MM, 1)
			if A[i][j] == -1:
				S = i * W + j
				sx = j; sy = i
				A[i][j] = 1
			if A[i][j] == -2:
				T = i * W + j
				tx = j; ty = i
				A[i][j] = 1

	for i in range(H):
		for j in range(W):
			if A[i][j] == 1:
				for k in range(j + 1, W):
					if A[i][k] == 1:
						DD.add_edge(i * W + j + MM, i * W + k, 1)
						DD.add_edge(i * W + k + MM, i * W + j, 1)

	for i in range(H):
		for j in range(W):
			if A[i][j] == 1:
				for k in range(i + 1, H):
					if A[k][j] == 1:
						DD.add_edge(i * W + j + MM, k * W + j, 1)
						DD.add_edge(k * W + j + MM, i * W + j, 1)

	ans = DD.flow(S + MM, T)
	if sx == tx or sy == ty:
		ans = -1
	print(ans)

if __name__ == '__main__':
	main()

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(10**7)

#ライブラリインポート
from collections import deque

#入力受け取り
def getlist():
	return list(map(int, input().split()))

INF = float("inf")

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

#処理内容
def main():
	H, W = getlist()
	A = []
	for i in range(H):
		a = list(input())
		A.append(a)
	
	S = None; T = None
	sx = None; sy = None
	tx = None; ty = None
	MM = H * W
	DD = Dinic(2 * MM)
	for i in range(H):
		for j in range(W):
			DD.add_edge(i * W + j, i * W + j + MM, 1)
			if A[i][j] == "S":
				S = i * W + j
				sx = j; sy = i
				A[i][j] = "o"
			if A[i][j] == "T":
				T = i * W + j
				tx = j; ty = i
				A[i][j] = "o"

	for i in range(H):
		for j in range(W):
			if A[i][j] == "o":
				for k in range(j + 1, W):
					if A[i][k] == "o":
						DD.add_edge(i * W + j + MM, i * W + k, 1)
						DD.add_edge(i * W + k + MM, i * W + j, 1)

	for i in range(H):
		for j in range(W):
			if A[i][j] == "o":
				for k in range(i + 1, H):
					if A[k][j] == "o":
						DD.add_edge(i * W + j + MM, k * W + j, 1)
						DD.add_edge(k * W + j + MM, i * W + j, 1)

	ans = DD.flow(S + MM, T)
	if sx == tx or sy == ty:
		ans = -1
	print(ans)

if __name__ == '__main__':
	main()

Submission status: Time Limit Exceeded

Solution code:

import sys
sys.setrecursionlimit(10**7)

#ライブラリインポート
from collections import deque

#入力受け取り
def getlist():
	return list(map(int, input().split()))

INF = float("inf")

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

class FordFulkerson:
	def __init__(self, N):
		self.N = N
		self.G = [[] for i in range(N)]

	#順の辺のフローを流した際に逆辺のcapを増加できるように処理
	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)

	#入力で順の辺と逆辺のcapが存在するときに使う？
	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)

	#流せる場所を探し、流せるだけ流した後に逆辺のcapを増やす
	#流せる場所がないなら打ち切り
	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 = 10 ** 9 + 7
		N = self.N
		while f:
			self.used = [0] * N
			f = self.dfs(s, t, INF)
			flow += f
		return flow



#処理内容
def main():
	H, W = getlist()
	A = []
	for i in range(H):
		a = list(input())
		A.append(a)
	
	S = None; T = None
	sx = None; sy = None
	tx = None; ty = None
	MM = H * W
	DD = FordFulkerson(2 * MM)

	# DD = Dinic(2 * MM)
	for i in range(H):
		for j in range(W):
			DD.add_edge(i * W + j, i * W + j + MM, 1)
			if A[i][j] == "S":
				S = i * W + j
				sx = j; sy = i
				A[i][j] = "o"
			if A[i][j] == "T":
				T = i * W + j
				tx = j; ty = i
				A[i][j] = "o"

	for i in range(H):
		for j in range(W):
			if A[i][j] == "o":
				for k in range(j + 1, W):
					if A[i][k] == "o":
						DD.add_edge(i * W + j + MM, i * W + k, 1)
						DD.add_edge(i * W + k + MM, i * W + j, 1)

	for i in range(H):
		for j in range(W):
			if A[i][j] == "o":
				for k in range(i + 1, H):
					if A[k][j] == "o":
						DD.add_edge(i * W + j + MM, k * W + j, 1)
						DD.add_edge(k * W + j + MM, i * W + j, 1)

	ans = DD.flow(S + MM, T)
	if sx == tx or sy == ty:
		ans = -1
	print(ans)

if __name__ == '__main__':
	main()

Submission status: Time Limit Exceeded

Solution code:
import sys
INF = 1 << 60
MOD = 10**9 + 7 # 998244353
sys.setrecursionlimit(2147483647)
input = lambda:sys.stdin.readline().rstrip()
import networkx as nx
def resolve():
    m, n = map(int, input().split())
    # row = 0, ..., m - 1, col = m, ..., m + n - 1, source = m + n, terminartion = m + n + 1
    G = nx.Graph()
    G.add_nodes_from(range(m + n + 2))
    grid = [input() for _ in range(m)]
    for i in range(m):
        for j in range(n):
            if grid[i][j] == 'S':
                si, sj = i, j
            elif grid[i][j] == 'T':
                ti, tj = i, j

    G.add_edge(m + n, si, capacity = INF)
    G.add_edge(m + n, m + sj, capacity = INF)
    G.add_edge(ti, m + n + 1, capacity = INF)
    G.add_edge(m + tj, m + n + 1, capacity = INF)
    for i in range(m):
        for j in range(n):
            if grid[i][j] == '.':
                continue
            for nj in range(n):
                if grid[i][nj] != '.':
                    G.add_edge(i, m + nj, capacity = 1)
            for ni in range(m):
                if grid[ni][j] != '.':
                    G.add_edge(ni, m + j, capacity = 1)

    ans = nx.algorithms.flow.maximum_flow_value(G, m + n, m + n + 1)
    if ans >= INF:
        ans = -1
    print(ans)
resolve()

Submission status: Time Limit Exceeded

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)
    from itertools import product
    target = ("o", "S", "T")
    for i,j in product(range(h), range(w)):
        if not a[i][j] in target:
            continue
        for k in range(h):
            if a[i][j] in target and a[k][j] in target:
                add(i,j,k,j)
                add(k,j,i,j)
        for k in range(w):
            if a[i][j] in target and a[i][k] in target:
                add(i,j,i,k)
                add(i,k,i,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).flow_value # startからの最短路木を求める
print(val)