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:
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**15

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

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)

for i in range(H):
    for j in range(W):
        if a[i][j] == 'S':
            start = i * W + j
        if a[i][j] == 'T':
            terminal = i * W + j

for i in range(H):
    for j in range(i+1, H):
        for k in range(W):
            if a[i][k] != '.' and a[j][k] != '.':
                mf.add_edge(W * i + k, W * j + k, 1)
                mf.add_edge(W * j + k, W * i + k, 1)

for i in range(W):
    for j in range(i+1, W):
        for k in range(H):
            if a[k][i] != '.' and a[k][j] != '.':
                mf.add_edge(W * k + i, W * k + j, 1)
                mf.add_edge(W * k + j, W * k + i, 1)

si, sj = divmod(start, W)
ti, tj = divmod(terminal, W)
if si == ti or sj == tj:
    print(-1)
else:
    print(mf.max_flow(start, terminal))

Submission status: Wrong Answer

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

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

ng = "."
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)
    elif a[h][w] == "o":
      flow.add_edge(h, H + w, 1)
      flow.add_edge(H + w, h, 1)

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

Submission status: Wrong Answer

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

ng = "."
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)
      flow.add_edge(s, H + w, H + W + 1)
    elif a[h][w] == "T":
      flow.add_edge(h, t, H + W)
      flow.add_edge(H + w, t, H + W + 1)
    elif a[h][w] == "o":
      flow.add_edge(h, H + w, 1)
      flow.add_edge(H + w, h, 1)

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

Submission status: Wrong Answer

Solution code:
import networkx as nx

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

G = nx.DiGraph()
for i in range(H):
  ok = []
  st = []
  stflag = -1
  for j in range(W):
    if a[i][j]=='o':
      ok.append(j)
    if a[i][j]=='S':
      start = (i,j)
      st.append(j)
      stflag=1
    if a[i][j]=='T':
      goal = (i,j)
      st.append(j)
      stflag=0
  if len(st)>1:
    print(-1)
    exit()
  for j1 in ok:
    for j2 in ok:
      G.add_edge(i*W+j1,i*W+j2,capacity=1)
      
  if st:
    j1 = st[0]
    if stflag==1:
      for j2 in ok:
        G.add_edge(i*W+j1,i*W+j2,capacity=1)
    else:
      for j2 in ok:
        G.add_edge(i*W+j2,i*W+j1,capacity=1)
        
for j in range(W):
  ok = []
  st = []
  stflag = -1
  for i in range(H):
    if a[i][j]=='o':
      ok.append(i)
    if a[i][j]=='S':
      start = (i,j)
      st.append(i)
      stflag=1
    if a[i][j]=='T':
      goal = (i,j)
      st.append(i)
      stflag=0
  if len(st)>1:
    print(-1)
    exit()
  for i1 in ok:
    for i2 in ok:
      G.add_edge(i1*W+j,i2*W+j,capacity=1)
      
  if st:
    i1 = st[0]
    if stflag==1:
      for i2 in ok:
        G.add_edge(i1*W+j,i2*W+j,capacity=1)
    else:
      for i2 in ok:
        G.add_edge(i2*W+j,i1*W+j,capacity=1)

s = start[0]*W+start[1]
t = goal[0]*W+goal[1]
nodes = set(G.nodes)
if (s not in nodes) or (t not in nodes):
  print(0)
  exit()
flow_value,flow_dict=nx.maximum_flow(G,s,t)
print(flow_value)

Submission status: Wrong Answer

Solution code:
import networkx as nx

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

G = nx.DiGraph()
for i in range(H):
  ok = []
  st = []
  stflag = -1
  for j in range(W):
    if a[i][j]=='o':
      ok.append(j)
    if a[i][j]=='S':
      start = (i,j)
      st.append(j)
      stflag=1
    if a[i][j]=='T':
      goal = (i,j)
      st.append(j)
      stflag=0
  if len(st)>1:
    print(-1)
    exit()
  for j1 in ok:
    for j2 in ok:
      G.add_edge(i*W+j1,i*W+j2,capacity=1)
      
  if st:
    j1 = st[0]
    if stflag==1:
      for j2 in ok:
        G.add_edge(i*W+j1,i*W+j2,capacity=1)
    else:
      for j2 in ok:
        G.add_edge(i*W+j2,i*W+j1,capacity=1)
        
for j in range(W):
  ok = []
  st = []
  stflag = -1
  for i in range(H):
    if a[i][j]=='o':
      ok.append(i)
    if a[i][j]=='S':
      start = (i,j)
      st.append(i)
      stflag=1
    if a[i][j]=='T':
      goal = (i,j)
      st.append(i)
      stflag=0
  if len(st)>1:
    print(-1)
    exit()
  for i1 in ok:
    for i2 in ok:
      G.add_edge(i1*W+j,i2*W+j,capacity=1)
      
  if st:
    i1 = st[0]
    if stflag==1:
      for i2 in ok:
        G.add_edge(i1*W+j,i2*W+j,capacity=1)
    else:
      for i2 in ok:
        G.add_edge(i2*W+j,i1*W+j,capacity=1)

s = start[0]*W+start[1]
t = goal[0]*W+goal[1]
nodes = set(G.nodes)
if (s not in nodes) or (t not in nodes):
  print(0)
  exit()
flow_value,flow_dict=nx.maximum_flow(G,s,t)
print(flow_value)

Submission status: Wrong Answer

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,...,H-1,W,..,W-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, INF)
                F.add_edge(s, w, INF)
            elif A[h][w] == "T":
                Th, Tw = h, w
                F.add_edge(h, 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: Wrong Answer

Solution code:
from collections import deque


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)
    s, t = -1, -1
    Sh, Sw = -1, -1
    Th, Tw = -1, -1
    for h in range(H):
        for w in range(W):
            if A[h][w] == "S":
                s = h*W + w
                Sh, Sw = h, w
            elif A[h][w] == "T":
                t = h*W + w
                Th, Tw = h, w
    if Sh == Th or Sw == Tw:
        return print(-1)

    for h in range(H):
        for w in range(W):
            if A[h][w] == "." or A[h][w] == "T":
                continue
            for dh in range(H):
                if dh != h and A[dh][w] == "o" or A[dh][w] == "T":
                    # G[h*W + w].append(dh*W + w)
                    cap = 100000 if A[dh][w] == "o" else 1
                    F.add_edge(h*W + w, dh*W + w, cap)
            for dw in range(W):
                if dw != W and A[h][dw] == "o" or A[h][dw] == "T":
                    # G[h*W + w].append(h*W + dw)
                    cap = 100000 if A[h][dw] == "o" else 1
                    F.add_edge(h*W + w, h*W + dw, cap)
    print(F.max_flow(s, t))


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

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 networkx as nx
    g = nx.DiGraph()
    for i in range(2*h*w):
        g.add_node(i)
    for i in range(h*w):
#         if i not in (start, goal):
        g.add_edge(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
        g.add_edge(2*u+1, 2*v, capacity=1)
        g.add_edge(2*v+1, 2*u, capacity=1)
    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)
    val = nx.maximum_flow(g, start, goal)[0]
print(val)

Submission status: Wrong Answer

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

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

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

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

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

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

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

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

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

    for h in range(H):
        for w in range(W):
            if A[h][w]==".":
                continue
            if A[h][w]=="S":
                din.add_link(0, h + W + 1, inf)
                din.add_link(0, w + 1, inf)
            if A[h][w]=="T":
                din.add_link(h + W + 1, H + W + 1, inf)
                din.add_link(w + 1, H + W + 1, inf)
            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
"""