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

Solution (Python):

from collections import defaultdict
from collections import deque
from heapq import heappush, heappop
import sys
import math
import bisect
import random
def LI(): return list(map(int, sys.stdin.readline().split()))
def I(): return int(sys.stdin.readline())
def LS():return list(map(list, sys.stdin.readline().split()))
def S(): return list(sys.stdin.readline())[:-1]
def IR(n):
    l = [None for i in range(n)]
    for i in range(n):l[i] = I()
    return l
def LIR(n):
    l = [None for i in range(n)]
    for i in range(n):l[i] = LI()
    return l
def SR(n):
    l = [None for i in range(n)]
    for i in range(n):l[i] = S()
    return l
def LSR(n):
    l = [None for i in range(n)]
    for i in range(n):l[i] = SR()
    return l
mod = 1000000007


def A():
    return


def B():
    return


def C():
    return


def D():
    return


def E():
    return


def F():
    def bfs(s,g,n):
        bfs_map = [-1 for i in range(n)]
        bfs_map[s] = 0
        q = deque()
        q.append(s)
        fin = False
        while q:
            x = q.popleft()
            for y in range(n):
                if c[x][y] > 0 and bfs_map[y] < 0:
                    bfs_map[y] = bfs_map[x]+1
                    if y == g:
                        fin = True
                        break
                    q.append(y)
            if fin:
                break

        if bfs_map[g] == -1:
            return [None,0]
        path = [None for i in range(bfs_map[g]+1)]
        m = float("inf")
        path[bfs_map[g]] = g
        y = g
        for i in range(bfs_map[g])[::-1]:
            for x in range(n+1):
                if c[x][y] > 0 and bfs_map[x] == bfs_map[y]-1:
                    path[i] = x
                    if c[x][y] < m:
                        m = c[x][y]
                    y = x
                    break
        return [path,m]

    def ford_fulkerson(s,g,c,n):
        while 1:
            p,m = bfs(s,g,n)
            if not m:break
            for i in range(len(p)-1):
                c[p[i]][p[i+1]] -= m
                c[p[i+1]][p[i]] += m
        return sum(c[g])
    h,w = LI()
    a = SR(h)
    c = [[0 for i in range(h+w+2)] for j in range(h+w+2)]
    for y in range(h):
        for x in range(w):
            if a[y][x] == "S":
                c[0][y+1] = float("inf")
                c[0][h+x+1] = float("inf")
            if a[y][x] == "T":
                c[y+1][h+w+1] = float("inf")
                c[h+x+1][h+w+1] = float("inf")
            if a[y][x] == "o":
                c[y+1][h+x+1] = 1
                c[h+x+1][y+1] = 1
    ans = ford_fulkerson(0,h+w+1,c,h+w+2)
    if ans == float("inf"):
        print(-1)
    else:
        print(ans)

def G():
    return


def H():
    return


if __name__ == "__main__":
    F()

Solution (Python):

from collections import defaultdict
from collections import deque
from heapq import heappush, heappop
import sys
import math
import bisect
import random
def LI(): return list(map(int, sys.stdin.readline().split()))
def I(): return int(sys.stdin.readline())
def LS():return list(map(list, sys.stdin.readline().split()))
def S(): return list(sys.stdin.readline())[:-1]
def IR(n):
    l = [None for i in range(n)]
    for i in range(n):l[i] = I()
    return l
def LIR(n):
    l = [None for i in range(n)]
    for i in range(n):l[i] = LI()
    return l
def SR(n):
    l = [None for i in range(n)]
    for i in range(n):l[i] = S()
    return l
def LSR(n):
    l = [None for i in range(n)]
    for i in range(n):l[i] = SR()
    return l
mod = 1000000007


def A():
    return


def B():
    return


def C():
    return


def D():
    return


def E():
    return


def F():
    def bfs(s,g,n):
        bfs_map = [-1 for i in range(n)]
        bfs_map[s] = 0
        q = deque()
        q.append(s)
        fin = False
        while q:
            x = q.popleft()
            for y in range(n):
                if c[x][y] > 0 and bfs_map[y] < 0:
                    bfs_map[y] = bfs_map[x]+1
                    if y == g:
                        fin = True
                        break
                    q.append(y)
            if fin:
                break

        if bfs_map[g] == -1:
            return [None,0]
        path = [None for i in range(bfs_map[g]+1)]
        m = float("inf")
        path[bfs_map[g]] = g
        y = g
        for i in range(bfs_map[g])[::-1]:
            for x in range(n+1):
                if c[x][y] > 0 and bfs_map[x] == bfs_map[y]-1:
                    path[i] = x
                    if c[x][y] < m:
                        m = c[x][y]
                    y = x
                    break
        return [path,m]

    def ford_fulkerson(s,g,c,n):
        while 1:
            p,m = bfs(s,g,n)
            if not m:break
            for i in range(len(p)-1):
                c[p[i]][p[i+1]] -= m
                c[p[i+1]][p[i]] += m
        return sum(c[g])
    h,w = LI()
    a = SR(h)
    c = [[0 for i in range(h+w+2)] for j in range(h+w+2)]
    for y in range(h):
        for x in range(w):
            if a[y][x] == "S":
                c[0][y+1] = float("inf")
                c[0][h+x+1] = float("inf")
            if a[y][x] == "T":
                c[y+1][h+w+1] = float("inf")
                c[h+x+1][h+w+1] = float("inf")
            if a[y][x] == "o":
                c[y+1][h+x+1] = 1
                c[h+x+1][y+1] = 1
    ans = ford_fulkerson(0,h+w+1,c,h+w+2)
    if ans == float("inf"):
        print(-1)
    else:
        print(ans)

def G():
    return


def H():
    return


if __name__ == "__main__":
    F()

Solution (Python):
import sys
input=sys.stdin.readline
sys.setrecursionlimit(10**9)
from collections import deque

class Dinic:
    def __init__(self,n,edges):
        self.n=n
        self.edges=[[] for _ in range(n)]
        self.iter=[0]*n
        self.level=None
        self.graph(edges)
    def graph(self,E):
        edges=self.edges
        for fr,to,cap in E:
            edges[fr].append([to,cap,len(edges[to])])
            edges[to].append([fr,0,len(edges[fr])-1])
    def maxflow(self,source,sink):
        max_flow=0
        while True:
            self.bfs(source)
            if self.level[sink]<0:
                return max_flow
            self.iter=[0]*self.n
            flow=self.dfs(source,sink,float('inf'))
            while flow:
                max_flow+=flow
                flow=self.dfs(source,sink,float('inf'))
    def bfs(self,source):
        edges=self.edges
        level=[-1]*self.n
        level[source]=0
        q=deque([source])
        while q:
            fr=q.popleft()
            for to,cap,_ in edges[fr]:
                if cap>0>level[to]:
                    level[to]=level[fr]+1
                    q.append(to)
        self.level=level
    def dfs(self,source,sink,flow):
        if source==sink:
            return flow
        while self.iter[source]<len(self.edges[source]):
            to,cap,rev=self.edges[source][self.iter[source]]
            if cap>0 and self.level[source]<self.level[to]:
                f=self.dfs(to,sink,min(flow,cap))
                if f:
                    self.edges[source][self.iter[source]][1]-=f
                    self.edges[to][rev][1]+=f
                    return f
            self.iter[source]+=1
        return 0

inf=float('inf')
h,w=map(int,input().split())
Edges=[]
for x in range(h):
    s=list(input())
    for y in range(w):
        if s[y]=='S':
            Edges.append((0,x+1,inf))
            Edges.append((0,y+1+h,inf))
        elif s[y]=='T':
            Edges.append((x+1,h+w+1,inf))
            Edges.append((y+1+h,h+w+1,inf))
        elif s[y]=='o':
            Edges.append((x+1,y+1+h,1))
            Edges.append((y+1+h,x+1,1))
dinic=Dinic(h+w+2,Edges)
mf=dinic.maxflow(0,h+w+1)
print(-1 if mf==inf else mf)

Solution (Python):
import sys
sys.setrecursionlimit(10**8)
class FK:
    def __init__(self,n):
        self.table=[[0]*n for i in range(n)]
        self.n=n
    
    def add(self,x,y,f):
        self.table[x][y]=f
        
    def ford(self,s,t,f):
        self.visit[s]=True
        if s==t:
            return f
        for i in range(self.n):
            if (not self.visit[i]) and self.table[s][i]>0:
                df=self.ford(i,t,min(f,self.table[s][i]))
                if df>0:
                    self.table[s][i]-=df
                    self.table[i][s]+=df
                    return df
        return 0
    
    def flow(self,s,t):
        ans=0
        inf=10**20
        while True:
            self.visit=[False]*(self.n)
            df=self.ford(s,t,inf)
            if df==0:
                break
            ans+=df
        return ans

H,W=map(int,input().split())
C=[input() for i in range(H)]
maxflow=FK(W+H+2)
inf=10**20
for i in range(W):
    for j in range(H):
        if C[j][i]=='S':
            sx=i
            sy=j
            maxflow.add(0,i+1,inf)
            maxflow.add(0,W+1+j,inf)
            continue
        if C[j][i]=='T':
            gx=i
            gy=j
            maxflow.add(i+1,W+H+1,inf)
            maxflow.add(W+1+j,W+H+1,inf)
            continue
        if C[j][i]=='o':
            maxflow.add(i+1,W+1+j,1)
            maxflow.add(W+1+j,i+1,1)

if gx==sx or gy==sy:
    print('-1')
    sys.exit()
ans=maxflow.flow(0,H+W+1)
print(ans)

Solution (Python):

from collections import defaultdict

def ford_fulkerson(graph, start, end):
    """ 
    graph: [dict<int,int>]
    start: int
    end: int
    """
    INF = 10**9
    network = [defaultdict(int, paths) for paths in graph]

    def dfs(start, end, visited):
        """
        None: unreachable
        (): reached
        """
        if start == end:
            return ()
        visited.add(start)
        for next_, capacity in filter(lambda next_capacity: next_capacity[0] not in visited and next_capacity[1] > 0, network[start].items()):
            path = dfs(next_, end, visited)
            if path is not None:
                return (next_, capacity, path)
        return None

    def margin(path, min_margin=INF):
        if path == ():
            return min_margin
        _, capacity, remaining_path = path
        return margin(remaining_path, min(min_margin, capacity))

    def flush(start, path, amount):
        if path == ():
            return
        next_, _, remaining_path = path
        network[start][next_] -= amount
        network[next_][start] += amount
        flush(next_, remaining_path, amount)

    while True:
        path = dfs(start, end, set())
        if path == None:
            break
        flush(start, path, margin(path))

    return sum(cap for _, cap in graph[start].items()) - sum(cap for _, cap in network[start].items())

h, w = map(int, input().split())
A = [input() for _ in range(h)]

for i in range(h):
    for j in range(w):
        if A[i][j] == 'S':
            s = (i, j)
        if A[i][j] == 'T':
            t = (i, j)

if t[0] == s[0] or t[1] == s[1]:
    print(-1)
else:
    INF = 10**8
    si = h + w
    ti = h + w + 1
    graph = [{} for _ in range(h + w + 2)]
    graph[si][s[0]] = INF
    graph[si][h + s[1]] = INF
    graph[t[0]][ti] = INF
    graph[h + t[1]][ti] = INF
    for i in range(h):
        for j in range(w):
            if A[i][j] == 'o':
                graph[i][h + j] = 1
                graph[h + j][i] = 1
    print(ford_fulkerson(graph, si, ti))

Solution (Python):
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools

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

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

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

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

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

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

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

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

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

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

        return flow

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

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




print(main())

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