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:
from collections import deque


class MaxFlow:
    """
    Example.

    mf = MaxFlow(N)
    mf.add_edge(0, 1, 1)
    mf.add_edge(1, 2, 3)

    print(mf.max_flow(0, 2))

    for fr, to, cap, flow in mf.edges():
        print(fr, to, flow)

    """
    def __init__(self, n):
        self.n = n
        self.graph = [[] for _ in range(n)]
        self.pos = []

    def add_edge(self, fr, to, cap):
        m = len(self.pos)
        self.pos.append((fr, len(self.graph[fr])))
        self.graph[fr].append([to, len(self.graph[to]), cap])
        self.graph[to].append([fr, len(self.graph[fr]) - 1, 0])
        return m

    def get_edge(self, idx):
        to, rev, cap = self.graph[self.pos[idx][0]][self.pos[idx][1]]
        rev_to, rev_rev, rev_cap = self.graph[to][rev]
        return rev_to, to, cap + rev_cap, rev_cap

    def edges(self):
        m = len(self.pos)
        for i in range(m):
            yield self.get_edge(i)

    def change_edge(self, idx, new_cap, new_flow):
        to, rev, cap = self.graph[self.pos[idx][0]][self.pos[idx][1]]
        self.graph[self.pos[idx][0]][self.pos[idx][1]][2] = new_cap - new_flow
        self.graph[to][rev][2] = new_flow

    def dfs(self, s, v, up):
        if v == s:
            return up
        res = 0
        lv = self.level[v]
        for i in range(self.iter[v], len(self.graph[v])):
            to, rev, cap = self.graph[v][i]
            if lv <= self.level[to] or self.graph[to][rev][2] == 0:
                continue
            d = self.dfs(s, to, min(up - res, self.graph[to][rev][2]))
            if d <= 0:
                continue
            self.graph[v][i][2] += d
            self.graph[to][rev][2] -= d
            res += d
            if res == up:
                break
            self.iter[v] += 1
        return res

    def max_flow(self, s, t):
        return self.max_flow_with_limit(s, t, 2 ** 63 - 1)

    def max_flow_with_limit(self, s, t, limit):
        flow = 0
        while flow < limit:
            self.level = [-1] * self.n
            self.level[s] = 0
            queue = deque()
            queue.append(s)
            while queue:
                v = queue.popleft()
                for to, rev, cap in self.graph[v]:
                    if cap == 0 or self.level[to] >= 0:
                        continue
                    self.level[to] = self.level[v] + 1
                    if to == t:
                        break
                    queue.append(to)
            if self.level[t] == -1:
                break
            self.iter = [0] * self.n
            while flow < limit:
                f = self.dfs(s, t, limit - flow)
                if not f:
                    break
                flow += f
        return flow

    def min_cut(self, s):
        visited = [0] * self.n
        queue = deque()
        queue.append(s)
        while queue:
            p = queue.popleft()
            visited[p] = True
            for to, rev, cap in self.graph[p]:
                if cap and not visited[to]:
                    visited[to] = True
                    queue.append(to)
        return visited


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

mf = MaxFlow(H + W + 2)
start = H + W
terminal = H + W + 1
INF = 10**6

for i in range(H):
    for j in range(W):
        if a[i][j] == 'S':
            mf.add_edge(start, i, INF)
            mf.add_edge(start, H + j, INF)
        elif a[i][j] == 'T':
            mf.add_edge(i, terminal, INF)
            mf.add_edge(H + j, terminal, INF)
        elif a[i][j] == 'o':
            mf.add_edge(i, H + j, 1)
            mf.add_edge(H + j, i, 1)

ans = mf.max_flow(start, terminal)
if ans >= INF:
    print(-1)
else:
    print(ans)

Submission status: Accepted

Solution code:
import sys

sys.setrecursionlimit(10**7)
def MI(): return map(int,sys.stdin.readline().rstrip().split())
def LS2(): return list(sys.stdin.readline().rstrip())


from collections import deque


class Dinic:
    def __init__(self, N, inf):
        self.N = N
        self.inf = inf
        self.G = [[] for _ in range(N)]
        self.level = [0]*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):
        self.level = [-1]*self.N
        deq = deque([s])
        self.level[s] = 0
        while deq:
            v = deq.pop()
            lv = self.level[v] + 1
            for w, cap, _ in self.G[v]:
                if cap > 0 and self.level[w] == -1:
                    self.level[w] = lv
                    deq.appendleft(w)

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

    def flow(self, s, t):
        flow = 0
        while True:
            self.bfs(s)
            if self.level[t] == -1:
                return flow
            *self.iter, = map(iter, self.G)
            f = self.inf
            while f > 0:
                f = self.dfs(s, t, self.inf)
                flow += f


H,W = MI()
inf = 10**5
Di = Dinic(H+W+2,inf)
s,t = H+W,H+W+1
for i in range(H):
    S = LS2()
    for j in range(W):
        if S[j] == 'S':
            Di.add_edge(s,i,inf)
            Di.add_edge(s,j+H,inf)
        elif S[j] == 'T':
            Di.add_edge(i,t,inf)
            Di.add_edge(j+H,t,inf)
        elif S[j] == 'o':
            Di.add_edge(i,j+H,1)
            Di.add_edge(j+H,i,1)

ans = Di.flow(s,t)
print(ans if ans < inf else -1)

Submission status: Accepted

Solution code:
# 最大流
NUMERIC_LIMITS = 10 ** 18
import queue
class maxFlow:
  class edge:
    def __init__(s, frm, to, cap, flow):
      s.frm, s.to = frm, to
      s.cap, s.flow = cap, flow

  def __init__(s, n):
    s._n = n
    s.g = [[] for _ in range(n)]
    s.pos = []

  def add_edge(s, frm, to, cap):
    m = len(s.pos)
    s.pos.append([frm, len(s.g[frm])])
    s.g[frm].append(s._edge(to, len(s.g[to]), cap))
    s.g[to].append(s._edge(frm,len(s.g[frm]) - 1, 0))
    return m

  def get_edge(s, i):
    m = len(s.pos)
    _e = s.g[s.pos[i][0]][s.pos[i][1]]
    _re = s.g[_e.to][_e.rev]
    return s.edge(s.pos[i][0], _e.to, _e.cap + _re.cap, _re.cap)

  def edges(s):
    m = len(s.pos)
    result = []
    for i in range(m):
      result.append(s.get_edge(i))
    return result

  def change_edge(s, i, new_cap, new_flow):
    m = len(s.pos)
    _e = s.g[s.pos[i].to][s.pos[i].rev]
    _re = s.g[_e.to][_e.rev]
    _e.cap = new_cap - new_flow
    _re.cap = new_flow

  def flow(self, s, t, flow_limit = NUMERIC_LIMITS):
    level = [0] * self._n
    iter = [0] * self._n 

    def bfs():
      for i in range(self._n):
        level[i] = -1
      level[s] = 0
      que = queue.Queue()
      que.put(s)
      while not que.empty():
        v = que.get()
        for e in self.g[v]:
           if e.cap == 0 or level[e.to] >= 0: continue
           level[e.to] = level[v] + 1
           if e.to == t: return
           que.put(e.to)
    def dfs(this, v, up):
      if v == s: return up
      res = 0
      level_v = level[v]
      for i in range(iter[v], len(self.g[v])):
        e = self.g[v][i]
        if level_v <= level[e.to] or self.g[e.to][e.rev].cap == 0: continue
        d = this(this, e.to, min(up - res, self.g[e.to][e.rev].cap))
        if d <= 0: continue
        self.g[v][i].cap += d
        self.g[e.to][e.rev].cap -= d
        res += d
        if res == up: break
      return res

    flow = 0
    while flow < flow_limit:
      bfs()
      if level[t] == -1: break
      for i in range(self._n): iter[i]
      while flow < flow_limit:
        f = dfs(dfs, t, flow_limit - flow)
        if not f: break
        flow += f
    return flow

  def min_cut(self, s):
    visited = [False] * self._n
    que = queue.Queue()
    que.put(s)
    while not que.empty():
      p = que.get()
      visited[p] = True
      for e in self.g[p]:
        if e.cap and not visited[e.to]:
          visited[e.to] = True
          que.put(e.to)
    return visited

  class _edge:
    def __init__(s, to, rev, cap):
      s.to, s.rev = to, rev
      s.cap = cap

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

flow = maxFlow(H + W + 2)
s = H + W
t = H + W + 1
for h in range(H):
  for w in range(W):
    if a[h][w] == "S":
      flow.add_edge(s, h, H + W + 1)
      flow.add_edge(s, H + w, H + W + 1)
    elif a[h][w] == "T":
      flow.add_edge(h, t, H + W + 1)
      flow.add_edge(H + w, t, H + W + 1)
    if a[h][w] != ".":
      flow.add_edge(h, H + w, 1)
      flow.add_edge(H + w, h, 1)

ans = flow.flow(s, t)
if ans > H + W:
  print(-1)
else:
  print(ans)

Submission status: Accepted

Solution code:
import networkx as nx

H,W = map(int,input().split())
a = [input() for _ in range(H)]
INF = 10**20

G = nx.Graph()
G.add_nodes_from(range(0,H+W+2))
for i in range(H):
  for j in range(W):
    if a[i][j]=='o':
      G.add_edge(i+1,j+H+1,capacity=1)
    if a[i][j]=='S':
      G.add_edge(0,i+1,capacity=INF)
      G.add_edge(0,j+H+1,capacity=INF)
    if a[i][j]=='T':
      G.add_edge(H+W+1,i+1,capacity=INF)
      G.add_edge(H+W+1,j+H+1,capacity=INF)
      
flow_value,flow_dict = nx.maximum_flow(G,0,H+W+1)
print(flow_value if flow_value < INF else -1)

Submission status: Accepted

Solution code:
# 解説AC、辺の張り方が難しすぎる
from collections import deque
INF = 1 << 23


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

    def add_edge(self, u, v, cap):
        self.G[u].append([v, cap, len(self.G[v])])
        self.G[v].append([u, 0, len(self.G[u])-1])

    def bfs(self, s):
        self.level = [-1] * self.N
        que = deque([s])
        self.level[s] = 0
        while que:
            u = que.popleft()
            for (v, cap, _) in self.G[u]:
                if cap > 0 and self.level[v] < 0:
                    self.level[v] = self.level[u] + 1
                    que.append(v)

    def dfs(self, u, t, f):
        if u == t:
            return f
        for i in range(self.progress[u], len(self.G[u])):
            self.progress[u] = i
            (v, cap, rev) = self.G[u][i]
            if cap > 0 and self.level[u] < self.level[v]:
                d = self.dfs(v, t, min(f, cap))
                if d > 0:
                    self.G[u][i][1] -= d
                    self.G[v][rev][1] += d
                    return d
        return 0

    def max_flow(self, s, t):
        flow = 0
        INF = 10**9
        while True:
            self.bfs(s)
            if self.level[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)


def main():
    H, W = (int(i) for i in input().split())
    A = [input() for i in range(H)]
    F = Dinic(H+W+2)  # 0,1,...,W-1,0,..,H-1,s,t
    s = H+W
    t = H+W+1
    for h in range(H):
        for w in range(W):
            if A[h][w] == "S":
                F.add_edge(s, h+W, INF)
                F.add_edge(s, w, INF)
            elif A[h][w] == "T":
                F.add_edge(h+W, t, INF)
                F.add_edge(w, t, INF)
            if A[h][w] != ".":
                F.add_edge(h+W, w, 1)
                F.add_edge(w, h+W, 1)

    ans = F.max_flow(s, t)
    if INF <= ans:
        print(-1)
    else:
        print(ans)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
# 解説AC、辺の張り方が難しすぎる
from collections import deque
INF = 1 << 23


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

    def add_edge(self, u, v, cap):
        self.G[u].append([v, cap, len(self.G[v])])
        self.G[v].append([u, 0, len(self.G[u])-1])

    def bfs(self, s):
        self.level = [-1] * self.N
        que = deque([s])
        self.level[s] = 0
        while que:
            u = que.popleft()
            for (v, cap, _) in self.G[u]:
                if cap > 0 and self.level[v] < 0:
                    self.level[v] = self.level[u] + 1
                    que.append(v)

    def dfs(self, u, t, f):
        if u == t:
            return f
        for i in range(self.progress[u], len(self.G[u])):
            self.progress[u] = i
            (v, cap, rev) = self.G[u][i]
            if cap > 0 and self.level[u] < self.level[v]:
                d = self.dfs(v, t, min(f, cap))
                if d > 0:
                    self.G[u][i][1] -= d
                    self.G[v][rev][1] += d
                    return d
        return 0

    def max_flow(self, s, t):
        flow = 0
        INF = 10**9
        while True:
            self.bfs(s)
            if self.level[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)


def main():
    H, W = (int(i) for i in input().split())
    A = [input() for i in range(H)]
    F = Dinic(H+W+2)  # 0,1,...,W-1,0,..,H-1,s,t
    s = H+W
    t = H+W+1
    Sh, Sw = -1, -1
    Th, Tw = -1, -1
    for h in range(H):
        for w in range(W):
            if A[h][w] == "S":
                Sh, Sw = h, w
                F.add_edge(s, h+W, INF)
                F.add_edge(s, w, INF)
            elif A[h][w] == "T":
                Th, Tw = h, w
                F.add_edge(h+W, t, INF)
                F.add_edge(w, t, INF)
            if A[h][w] != ".":
                F.add_edge(h+W, w, 1)
                F.add_edge(w, h+W, 1)
    if Sh == Th or Sw == Tw:
        return print(-1)

    print(F.max_flow(s, t))


if __name__ == '__main__':
    main()

Submission status: Accepted

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())
    # source = -1, row = 0, ..., m - 1, col = m, ..., m + n - 1, terminartion = m + n
    G = nx.Graph()
    G.add_nodes_from(range(m + n + 2))
    for i in range(m):
        for j, c in enumerate(input()):
            if c == '.':
                continue
            elif c == 'o':
                G.add_edge(i, m + j, capacity = 1)
            elif c == 'S':
                G.add_edge(-1, i, capacity = INF)
                G.add_edge(-1, m + j, capacity = INF)
            elif c == 'T':
                G.add_edge(i, m + n, capacity = INF)
                G.add_edge(m + j, m + n, capacity = INF)

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

Submission status: Accepted

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()))
data= []
rs = []
cs = []
for i in range(h):
    c = input()
    if "S" in c:
        start = (i, c.index("S"))
    if "T" in c:
        goal = (i, c.index("T"))
    for j in range(w):
        if c[j] in ("o"):#, "S", "T"):
            data.append(1)
            rs.append(i)
            cs.append(h+j)
            data.append(1)
            rs.append(h+j)
            cs.append(i)
s = h+w
t = h+w+1
V = 10**9
data.append(V)
rs.append(s)
cs.append(start[0])
# data.append(V)
# rs.append(start[0])
# cs.append(s)

data.append(V)
rs.append(s)
cs.append(start[1]+h)
# data.append(V)
# rs.append(start[1]+h)
# cs.append(s)

data.append(V)
rs.append(goal[0])
cs.append(t)
# data.append(V)
# rs.append(t)
# cs.append(goal[0])

# data.append(V)
# rs.append(t)
# cs.append(goal[1]+h)
data.append(V)
rs.append(goal[1]+h)
cs.append(t)

import scipy.sparse
m = scipy.sparse.csr_matrix((data, (rs, cs)), shape=(h+w+2,h+w+2))
val = scipy.sparse.csgraph.maximum_flow(m, s, t).flow_value
if val>=10**9:
    val = -1
print(val)

Submission status: Accepted

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()))
data= []
rs = []
cs = []
for i in range(h):
    c = input()
    if "S" in c:
        start = (i, c.index("S"))
    if "T" in c:
        goal = (i, c.index("T"))
    for j in range(w):
        if c[j] in ("o"):#, "S", "T"):
            data.append(1)
            rs.append(i)
            cs.append(h+j)
            data.append(1)
            rs.append(h+j)
            cs.append(i)
s = h+w
t = h+w+1
V = 10**9
data.append(V)
rs.append(s)
cs.append(start[0])
data.append(V)
rs.append(start[0])
cs.append(s)

data.append(V)
rs.append(s)
cs.append(start[1]+h)
data.append(V)
rs.append(start[1]+h)
cs.append(s)

data.append(V)
rs.append(goal[0])
cs.append(t)
data.append(V)
rs.append(t)
cs.append(goal[0])

data.append(V)
rs.append(t)
cs.append(goal[1]+h)
data.append(V)
rs.append(goal[1]+h)
cs.append(t)

import scipy.sparse
m = scipy.sparse.csr_matrix((data, (rs, cs)), shape=(h+w+2,h+w+2))
val = scipy.sparse.csgraph.maximum_flow(m, s, t).flow_value
if val>=10**9:
    val = -1
print(val)

Submission status: Accepted

Solution code:

"""

https://atcoder.jp/contests/arc074/tasks/arc074_d
適当に最小カットを求めればいい
→縦横を別ノードで持っておいてつなぐ

0～99 列
100～199 横
200 = start
201 = goal

"""



from collections import defaultdict
from collections import deque

def Ford_Fulkerson_Func(s,g,lines,cost):

    N = len(cost)
    ans = 0
    queue = deque([ [s,float("inf")] ])

    ed = [True] * N
    ed[s] = False

    route = [0] * N
    route[s] = -1

    while queue:

        now,flow = queue.pop()
        for nex in lines[now]:

            if ed[nex]: 
                flow = min(cost[now][nex],flow)
                route[nex] = now
                queue.append([nex,flow])
                ed[nex] = False

                if nex == g:
                    ans += flow
                    break
            
        else:
            continue
        break

    else:
        return False,ans


    t = g
    s = route[t]

    while s != -1:
        cost[s][t] -= flow
        if cost[s][t] == 0:
            lines[s].remove(t)

        if cost[t][s] == 0:
            lines[t].add(s)
        cost[t][s] += flow
        t = s
        s = route[t]

    return True,ans

def Ford_Fulkerson(s,g,lines,cost):

    ans = 0

    while True:
        fl,nans = Ford_Fulkerson_Func(s,g,lines,cost)

        if fl:
            ans += nans
            continue
        else:
            break
    
    return ans

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

lines = defaultdict(set)
cost = [ [0] * 202 for i in range(202) ]

for i in range(H):

    a = input()
    for j in range(W):
        if a[j] == "S":
            lines[200].add(i)
            cost[200][i] = 20000

            lines[200].add(100+j)
            cost[200][100+j] = 20000

        elif a[j] == "T":
            lines[i].add(201)
            cost[i][201] = 20000

            lines[100+j].add(201)
            cost[j+100][201] = 20000
    
        elif a[j] == "o":
            lines[i].add(j+100)
            cost[i][j+100] = 1
            lines[j+100].add(i)
            cost[j+100][i] = 1

ans = (Ford_Fulkerson(200,201,lines,cost))
if ans >= 20000:
    print (-1)
else:
    print (ans)

Submission status: Accepted

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]=="S":
                din.add_link(0, h + W + 1, inf)
                din.add_link(0, w + 1, inf)
            elif A[h][w]=="T":
                din.add_link(h + W + 1, H + W + 1, inf)
                din.add_link(w + 1, H + W + 1, inf)
            elif A[h][w]=="o":
                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: Accepted

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>M)or f)

Submission status: Accepted

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)
print([-1,f:=minimum_cut(g,M,I)[0]][f<I])

Submission status: Accepted

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

Submission status: Accepted

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*2,h:=i//W],[m*2,w:=i%W+m]]*((c:=S[h][w-m])=='S')+[[h,I:=m*3],[w,I]]*(c=='T'),capacity=I),a([[h,w],[w,h]]*(c>'T'),capacity=1)
print([-1,f:=minimum_cut(g,m*2,I)[0]][f<I])

Submission status: Accepted

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*2,h:=i//W],[m*2,w:=i%W+m]]*((c:=S[h][w-m])=='S')+[[h,I:=m*3],[w,I]]*(c=='T'),capacity=I)
  a([[h,w],[w,h]]*(c>'T'),capacity=1)
print([-1,f:=minimum_cut(g,m*2,I)[0]][f<I])

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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(([999]*4+[1]*(len(A)//2-4),(A[::2], A[1::2])),(m*4,m*4)),m*2,m*3).flow_value;print(f if f<999 else -1)

Submission status: Accepted

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(([999]*4+[1]*(len(A)//2-4),(A[::2], A[1::2])),shape=(m*4,m*4)),m*2,m*3).flow_value;print(f if f<999 else -1)

Submission status: Accepted

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

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);A=[m*2,h,m*2,w+m]+A if S[h][w]=='S' else [h,m*3,w+m,m*3]+A if S[h][w]=='T' else A+[h,w+m,w+m,h] if S[h][w]=='o' else A
f=maximum_flow(csr_matrix(([9**9]*4+[1]*(len(A)//2-4),(A[::2], A[1::2])),shape=(m*4,m*4)),m*2,m*3).flow_value;print(f if f<9**9 else -1)

Submission status: Accepted

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