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: 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)
    for i in range(h):
        index = []
        for j in range(w):
            if a[i][j] in ("o", "S", "T"):
                index.append(j)
        for x in index:
            for y in index:
                if x!=y:
                    add(i,x,i,y)
    for j in range(w):
        index = []
        for i in range(h):
            if a[i][j] in ("o", "S", "T"):
                index.append(i)
        for x in index:
            for y in index:
                if x!=y:
                    add(x,j,y,j)
    m = scipy.sparse.csr_matrix((data, (rs, cs)), shape=(2*h*w, 2*h*w))
    val = scipy.sparse.csgraph.maximum_flow(m, start, goal).flow_value # startからの最短路木を求める
print(val)

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 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, capacity=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: Time Limit Exceeded

Solution code:
import sys#if RE->suspect recursion limit error
from collections import deque
sys.setrecursionlimit(10000)

class Dinic:
    """max-flow-min-cut
    faster than ford-fulkerson algorithm
    O(|V||E|)
    """

    def __init__(self,V:int):
        """
        Arguments:
            V:num of vertex
            adj:adjedscent list(adj[from]=(to,capacity,id))
        """
        self.V = V
        self.adj=[[] for _ in range(V)]
        self.level=[-1]*self.V
        self.iter=[-1]*self.V

    def add_edge(self,fro:int,to:int,cap:int):
        """
        Arguments:
            fro:from
            to: to
            cap: capacity of the edge
            f: max flow value
        """
        #edge
        self.adj[fro].append([to,cap,len(self.adj[to])])
        #rev edge
        self.adj[to].append([fro,0,len(self.adj[fro])-1])

    def bfs(self,s:int):
        """ bfs from s
        use deque to bfs
        """
        self.level=[-1]*self.V
        Q=deque()
        self.level[s]=0
        Q.append(s)

        while Q:
            v = Q.pop()
            for i in range(len(self.adj[v])):
                (nex_id,nex_cap,nex_rev) = self.adj[v][i]
                if nex_cap>0 and self.level[nex_id]<-0:
                    self.level[nex_id] = self.level[v]+1
                    Q.append(nex_id)


    def dfs(self,v,t,f):

        """
        search increasing path
        """
        if v==t:
            return f

        for i in range(self.iter[v],len(self.adj[v])):
            self.iter[v]=i
            (nex_id,nex_cap,nex_rev) = self.adj[v][i]
            if nex_cap>0 and self.level[v]<self.level[nex_id]:
                d = self.dfs(nex_id,t,min(f,nex_cap))
                if d>0:
                    #decrease capacity to denote use it with d flow
                    self.adj[v][i][1]-=d
                    self.adj[nex_id][nex_rev][1]+=d
                    return d
        return 0

    def max_flow(self,s:int,t:int):
        """calculate maxflow from s to t
        """
        flow=0
        self.used = [False]*self.V
        #while no increasing path is found
        while True:
            self.bfs(s)
            self.iter=[0]*self.V
            f = self.dfs(s,t,float("inf"))
            if f==0:
                return flow
            else:
                flow+=f


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

F = Dinic(H*W*2)
for i in range(H):
    for j in range(W):
        if grid[i][j]=="S":
            sy,sx = i,j
            grid[i][j]="o"
        if grid[i][j]=="T":
            gy,gx=i,j
            grid[i][j]="o"
        if grid[i][j]=="o":
            #in node and out node
            F.add_edge(i*W+j+H*W,i*W+j,1)

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

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




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

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(10000)
class FordFulkerson:
    """max-flow-min-cut
    O(F|E|)
    """

    def __init__(self,V:int):
        """
        Arguments:
            V:num of vertex
            adj:adjedscent list(adj[from]=(to,capacity,id))
        """
        self.V = V
        self.adj=[[] for _ in range(V)]
        self.used=[False]*V

    def add_edge(self,fro:int,to:int,cap:int):
        """
        Arguments:
            fro:from
            to: to
            cap: capacity of the edge
            f: max flow value
        """
        #edge
        self.adj[fro].append([to,cap,len(self.adj[to])])
        #rev edge
        self.adj[to].append([fro,0,len(self.adj[fro])-1])

    def dfs(self,v,t,f):
        """
        search increasing path
        """
        if v==t:
            return f
        self.used[v]=True
        for i in range(len(self.adj[v])):
            (nex_id,nex_cap,nex_rev) = self.adj[v][i]
            if not self.used[nex_id] and nex_cap>0:
                d = self.dfs(nex_id,t,min(f,nex_cap))
                if d>0:
                    #decrease capacity to denote use it with d flow
                    self.adj[v][i][1]-=d
                    self.adj[nex_id][nex_rev][1]+=d
                    return d
        return 0

    def max_flow(self,s:int,t:int):
        """calculate maxflow from s to t
        """
        flow=0
        self.used = [False]*self.V
        #while no increasing path is found
        while True:
            self.used = [False]*self.V
            f = self.dfs(s,t,float("inf"))
            if f==0:
                return flow
            else:
                flow+=f


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

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

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

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




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

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(10000)
class FordFulkerson:
    """max-flow-min-cut
    O(F|E|)
    """

    def __init__(self,V:int):
        """
        Arguments:
            V:num of vertex
            adj:adjedscent list(adj[from]=(to,capacity,id))
        """
        self.V = V
        self.adj=[[] for _ in range(V)]
        self.used=[False]*V

    def add_edge(self,fro:int,to:int,cap:int):
        """
        Arguments:
            fro:from
            to: to
            cap: capacity of the edge
            f: max flow value
        """
        #edge
        self.adj[fro].append([to,cap,len(self.adj[to])])
        #rev edge
        self.adj[to].append([fro,0,len(self.adj[fro])-1])

    def dfs(self,v,t,f):
        """
        search increasing path
        """
        if v==t:
            return f
        self.used[v]=True
        for i in range(len(self.adj[v])):
            (nex_id,nex_cap,nex_rev) = self.adj[v][i]
            if not self.used[nex_id] and nex_cap>0:
                d = self.dfs(nex_id,t,min(f,nex_cap))
                if d>0:
                    #decrease capacity to denote use it with d flow
                    self.adj[v][i][1]-=d
                    self.adj[nex_id][nex_rev][1]+=d
                    return d
        return 0

    def max_flow(self,s:int,t:int):
        """calculate maxflow from s to t
        """
        flow=0
        self.used = [False]*self.V
        #while no increasing path is found
        while True:
            self.used = [False]*self.V
            f = self.dfs(s,t,float("inf"))
            if f==0:
                return flow
            else:
                flow+=f


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

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

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

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




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

Submission status: Time Limit Exceeded

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

import sys
input = sys.stdin.readline

INF = 10**18

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


def make():
    state = [list(input().rstrip()) for _ in range(H)]
    graph = [{} for _ in range(2*V)]

    start = -1
    finish = -1

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


    for w in range(W):
        Node = []
        for h in range(H):
            if state[h][w] != ".":
                Node.append(h*W+w)
        L = len(Node)
        for i in range(L):
            v = Node[i]
            if v not in {start, finish}: v += V
            for j in range(i+1, L):
                u = Node[j]
                if u not in {start, finish}: u += V
                graph[u][v] = 1
                graph[v][u] = 1
    
    for i in range(V):
        if i != start and i != finish:
            u, v = i, i+V
            graph[u][v] = 1
            graph[v][u] = 1
    
    return graph, start, finish


def dfs2(start, finish, graph):
    Flow = [INF]*len(graph)
    used = [False]*len(graph)
    Par = [-1]*len(graph)
    stack = [start]
    used[start] = True
    while stack:
        v = stack.pop()
        if v == finish:
            d = Flow[v]
            while v != start:
                nv = Par[v]
                graph[nv][v] -= d
                graph[v][nv] += d
                v = nv
            return d, graph
        for i, (nv, ncap) in enumerate(graph[v].items()):
            if not used[nv] and ncap > 0:
                used[nv] = True
                stack.append(nv)
                Par[nv] = v
                Flow[nv] = min(Flow[v], ncap)
    return 0, graph

# solve
def max_flow(start, finish, graph):
    flow = 0
    while True:
        f, graph = dfs2(start, finish, graph)
        if f == 0: return flow
        flow += f


def main():
    graph, start, finish = make()
    ans = max_flow(start, finish, graph)

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


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

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

import sys
input = sys.stdin.readline

INF = 10**18

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


def make():
    state = [list(input().rstrip()) for _ in range(H)]
    graph = [{} for _ in range(2*V)]

    start = -1
    finish = -1

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


    for w in range(W):
        Node = []
        for h in range(H):
            if state[h][w] != ".":
                Node.append(h*W+w)
        L = len(Node)
        for i in range(L):
            v = Node[i]
            if v not in {start, finish}: v += V
            for j in range(i+1, L):
                u = Node[j]
                if u not in {start, finish}: u += V
                graph[u][v] = 1
                graph[v][u] = 1
    
    for i in range(V):
        if i != start and i != finish:
            u, v = i, i+V
            graph[u][v] = 1
            graph[v][u] = 1
    
    return graph, start, finish


def dfs2(start, finish, graph):
    Flow = [INF]*len(graph)
    used = [False]*len(graph)
    Par = [-1]*len(graph)
    stack = [start]
    used[start] = True
    while stack:
        v = stack.pop()
        if v == finish:
            d = Flow[v]
            while v != start:
                nv = Par[v]
                graph[nv][v] -= d
                if nv in graph[v]:
                    graph[v][nv] += d
                else:
                    graph[v][nv] = d
                if not graph[nv][v]:
                    del graph[nv][v]
                v = nv
            return d, graph
        for i, (nv, ncap) in enumerate(graph[v].items()):
            if not used[nv] and ncap > 0:
                used[nv] = True
                stack.append(nv)
                Par[nv] = v
                Flow[nv] = min(Flow[v], ncap)
    return 0, graph

# solve
def max_flow(start, finish, graph):
    flow = 0
    while True:
        f, graph = dfs2(start, finish, graph)
        if f == 0: return flow
        flow += f


def main():
    graph, start, finish = make()
    ans = max_flow(start, finish, graph)

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


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

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

import sys
input = sys.stdin.readline

INF = 10**18

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

def make():
    state = [list(input().rstrip()) for _ in range(H)]
    graph = [[] for _ in range(2*V)]

    start = -1
    finish = -1

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


    for w in range(W):
        Node = []
        for h in range(H):
            if state[h][w] != ".":
                Node.append(h*W+w)
        L = len(Node)
        for i in range(L):
            v = Node[i]
            if v not in {start, finish}: v += V
            for j in range(i+1, L):
                u = Node[j]
                if u not in {start, finish}: u += V
                graph[u].append([v, 1, len(graph[v])])
                graph[v].append([u, 1, len(graph[u])-1])
    
    for i in range(V):
        if i != start and i != finish:
            u, v = i, i+V
            graph[u].append([v, 1, len(graph[v])])
            graph[v].append([u, 1, len(graph[u])-1])
    
    return graph, start, finish


def dfs2(start, finish, graph):
    Flow = [-1]*len(graph)
    used = [False]*len(graph)
    Flow[start] = INF
    Par = [None]*len(graph)
    stack = [start]
    while stack:
        v = stack.pop()
        if v == finish:
            d = Flow[v]
            while v != start:
                nv, i, nrev = Par[v]
                graph[nv][i][1] -= d
                graph[v][nrev][1] += d
                v = nv
            return d, graph
        used[v] = True
        for i, (nv, ncap, nrev) in enumerate(graph[v]):
            if not used[nv] and ncap > 0:
                stack.append(nv)
                Par[nv] = (v, i, nrev)
                Flow[nv] = min(Flow[v], ncap)
    return 0, graph


# solve
def max_flow(start, finish, graph):
    flow = 0
    while True:
        f, graph = dfs2(start, finish, graph)
        if f == 0: return flow
        flow += f


def main():
    graph, start, finish = make()
    ans = max_flow(start, finish, graph)

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


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

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

import sys
input = sys.stdin.readline

INF = 10**18

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

def make():
    state = [list(input().rstrip()) for _ in range(H)]
    graph = [[] for _ in range(2*V)]

    start = -1
    finish = -1

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


    for w in range(W):
        Node = []
        for h in range(H):
            if state[h][w] != ".":
                Node.append(h*W+w)
        L = len(Node)
        for i in range(L):
            v = Node[i]
            if v not in {start, finish}: v += V
            for j in range(i+1, L):
                u = Node[j]
                if u not in {start, finish}: u += V
                graph[u].append([v, 1, len(graph[v])])
                graph[v].append([u, 1, len(graph[u])-1])
    
    for i in range(V):
        if i != start and i != finish:
            u, v = i, i+V
            graph[u].append([v, 1, len(graph[v])])
            graph[v].append([u, 1, len(graph[u])-1])
    
    return graph, start, finish


def dfs2(start, finish, graph):
    Flow = [-1]*len(graph)
    used = [False]*len(graph)
    Flow[start] = INF
    Par = [None]*len(graph)
    stack = [start]
    while stack:
        v = stack.pop()
        if v == finish:
            d = Flow[v]
            while v != start:
                nv, i, nrev = Par[v]
                graph[nv][i][1] -= d
                graph[v][nrev][1] += d
                v = nv
            return d
        used[v] = True
        for i, (nv, ncap, nrev) in enumerate(graph[v]):
            if not used[nv] and ncap > 0:
                stack.append(nv)
                Par[nv] = (v, i, nrev)
                Flow[nv] = min(Flow[v], ncap)
    return 0


# solve
def max_flow(start, finish, graph):
    flow = 0
    while True:
        f = dfs2(start, finish, graph)
        if f == 0: return flow
        flow += f


def main():
    graph, start, finish = make()
    ans = max_flow(start, finish, graph)

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


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

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

import sys
input = sys.stdin.readline

INF = 10**18

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

def make():
    state = [list(input().rstrip()) for _ in range(H)]
    graph = [[] for _ in range(2*V)]

    start = -1
    finish = -1

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


    for w in range(W):
        Node = []
        for h in range(H):
            if state[h][w] != ".":
                Node.append(h*W+w)
        L = len(Node)
        for i in range(L):
            v = Node[i]
            if v not in {start, finish}: v += V
            for j in range(i+1, L):
                u = Node[j]
                if u not in {start, finish}: u += V
                graph[u].append([v, 1, len(graph[v])])
                graph[v].append([u, 1, len(graph[u])-1])
    
    for i in range(V):
        if i != start and i != finish:
            u, v = i, i+V
            graph[u].append([v, 1, len(graph[v])])
            graph[v].append([u, 1, len(graph[u])-1])
    
    return graph, start, finish


used = [False]*V




def dfs2(start, finish, graph):
    Flow = [-1]*len(graph)
    Flow[start] = INF
    Par = [-1]*len(graph)
    stack = [start]
    while stack:
        v = stack.pop()
        if v == finish:
            d = Flow[v]
            while v != start:
                nv, i, nrev = Par[v]
                graph[nv][i][1] -= d
                graph[v][nrev][1] += d
                v = nv
            return d
        used[v] = True
        for i, (nv, ncap, nrev) in enumerate(graph[v]):
            if not used[nv] and ncap > 0:
                stack.append(nv)
                Par[nv] = (v, i, nrev)
                Flow[nv] = min(Flow[v], ncap)
    return 0


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


def main():
    graph, start, finish = make()
    ans = max_flow(start, finish, graph)

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


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

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

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

INF = 10**18

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

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

start = -1
finish = -1

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


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


used = [False]*V

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


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


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


ans = max_flow(start, finish)


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

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
H, W = map(int, input().split())
a = [list(input())[: -1] for _ in range(H)]
c = H + W - 1
class FordFulkerson:
    def __init__(self, N):
        self.N = N
        self.G = [[] for i in range(N)]

    def add_edge(self, fr, to, cap):
        forward = [to, cap, None]
        forward[2] = backward = [fr, 0, forward]
        self.G[fr].append(forward)
        self.G[to].append(backward)

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

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

    def flow(self, s, t):
        flow = 0
        f = INF = c
        N = self.N
        while f:
            #print(f)
            self.used = [0]*N
            f = self.dfs(s, t, INF)
            flow += f
        return flow
flk = FordFulkerson(H * W * 2 + H + W + 1)
b = H * W
s = 0
t = 0
for i in range(H):
  for j in range(W):
    if a[i][j] != ".":
      flk.add_edge(b + i * W + j, b * 2 + i, c)
      flk.add_edge(b * 2 + i, i * W + j, c)
for j in range(W):
  for i in range(H):
    if a[i][j] != ".":
      flk.add_edge(b + i * W + j, b * 2 + H + j, c)
      flk.add_edge(b * 2 + H + j, i * W + j, c)
for i in range(H):
  for j in range(W):
    if a[i][j] != ".":
      flk.add_edge(i * W + j, b + i * W + j, 1)
    if a[i][j] == "S": s = b + i * W + j
    if a[i][j] == "T": t = i * W + j
if (s - b) % W != t % W and ((s - b) // W != t // W): print(flk.flow(s, t))
else: print(-1)