Problem:


Score : 100 points

Problem Statement

You are given a grid of N rows and M columns. The square at the i-th row and j-th column will be denoted as (i,j).
Some of the squares contain an object. All the remaining squares are empty.
The state of the grid is represented by strings S_1,S_2,\cdots,S_N. The square (i,j) contains an object if S_{i,j}= # and is empty if S_{i,j}= ..

Consider placing 1 \times 2 tiles on the grid. Tiles can be placed vertically or horizontally to cover two adjacent empty squares.
Tiles must not stick out of the grid, and no two different tiles may intersect. Tiles cannot occupy the square with an object.

Calculate the maximum number of tiles that can be placed and any configulation that acheives the maximum.

Constraints

1 \leq N \leq 100

1 \leq M \leq 100

S_i is a string with length M consists of # and ..

Input

Input is given from Standard Input in the following format:

N M
S_1
S_2
\vdots
S_N

Output

On the first line, print the maximum number of tiles that can be placed.

On the next N lines, print a configulation that achieves the maximum.
Precisely, output the strings t_1,t_2,\cdots,t_N constructed by the following way.

t_i is initialized to S_i.

For each (i,j), if there is a tile that occupies (i,j) and (i+1,j), change t_{i,j}:=v, t_{i+1,j}:=^.

For each (i,j), if there is a tile that occupies (i,j) and (i,j+1), change t_{i,j}:=>, t_{i,j+1}:=<.

See samples for further information.

You may print any configulation that maximizes the number of tiles.

Sample Input 1

3 3
#..
..#
...

Sample Output 1

3
#><
vv#
^^.

The following output is also treated as a correct answer.

3
#><
v.#
^><



Sample input:
3 3
#..
..#
...


Sample output:
3
#><
vv#
^^.

Submission status: Accepted

Solution code:
def getN():
    return int(input())
def getNM():
    return map(int, input().split())
def getList():
    return list(map(int, input().split()))
def getArray(intn):
    return [int(input()) for i in range(intn)]
def input():
    return sys.stdin.readline().rstrip()
def rand_N(ran1, ran2):
    return random.randint(ran1, ran2)
def rand_List(ran1, ran2, rantime):
    return [random.randint(ran1, ran2) for i in range(rantime)]
def rand_ints_nodup(ran1, ran2, rantime):
  ns = []
  while len(ns) < rantime:
    n = random.randint(ran1, ran2)
    if not n in ns:
      ns.append(n)
  return sorted(ns)

def rand_query(ran1, ran2, rantime):
  r_query = []
  while len(r_query) < rantime:
    n_q = rand_ints_nodup(ran1, ran2, 2)
    if not n_q in r_query:
      r_query.append(n_q)
  return sorted(r_query)

from collections import defaultdict, deque, Counter
from sys import exit
from decimal import *
from heapq import heapify, heappop, heappush
import math
import random
import string
from copy import deepcopy
from itertools import combinations, permutations, product
from operator import mul, itemgetter
from functools import reduce
from bisect import bisect_left, bisect_right

import sys
sys.setrecursionlimit(1000000000)
mod = 10 ** 9 + 7

#############
# Main Code #
#############

N, M = getNM()
n = N # 保存用
m = M # 保存用
S = [list(input()) for i in range(N)]

# 変換1
def change(y, x):
    return y * M + (x + 1)

def change_rev(z):
    sz = z - 1
    y_opt = sz // m
    return y_opt, sz - m * y_opt

# 変換2
def change2(y, x):
    return N * M + y * M + (x + 1)

def change2_rev(z):
    sz = z - n * m - 1
    y_opt = sz // m
    return y_opt, sz - m * y_opt

query = []
for i in range(N):
    for j in range(M):
        if S[i][j] == '.':
            query.append([0, change(i, j), 1])
            query.append([change2(i, j), 2 * N * M + 1, 1])

dx = [1, 0, -1, 0]
dy = [0, 1, 0, -1]
for i in range(N):
    for j in range(M):
        if (i + j) % 2 == 0:
            continue
        for k in range(4):
            ny = i + dy[k]
            nx = j + dx[k]
            if 0 <= ny < N and 0 <= nx < M and S[i][j] == '.' and S[ny][nx] == '.':
                query.append([change(i, j), change2(ny, nx), 1])

query.sort()

N = 2 * N * M + 2
ans = 0
lines = defaultdict(set)
cost = defaultdict(lambda: defaultdict(int))
for i in range(len(query)):
    a, b, c = query[i]
    if c != 0:
        lines[a].add(b)
        cost[a][b] += c

def Ford_Fulkerson(sta, end):
    global ans
    queue = deque()
    queue.append([sta, float('inf')])

    ignore = [1] * N
    ignore[sta] = 0

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

    while queue:
        s, flow = queue.pop()
        for t in lines[s]:  #s->t
            if ignore[t]: #未到達
                # flowは入ってくる量、出る量のうち小さい方
                flow = min(cost[s][t], flow)
                route[t] = s
                queue.append([t, flow])
                ignore[t] = 0
                if t == end: #ゴール到達
                    ans += flow
                    break
        else:
            continue #breakされなければWhile節の先頭に戻る
        # Falseはされない
        break
    else:
        return False

    t = end
    s = route[t]
    # goalまで流れた量はflow
    # 逆向きの辺を貼る
    while s != -1:
        #s->tのコスト減少，ゼロになるなら辺を削除
        cost[s][t] -= flow
        if cost[s][t] == 0:
            lines[s].remove(t)
            #t->s(逆順)のコスト増加，元がゼロなら辺を作成
        if cost[t][s] == 0:
            lines[t].add(s)

        cost[t][s] += flow

        # 一つ上の辺をたどる
        t = s
        s = route[t]

    return True

while True:
    # ちょびちょび流して行ってゴールまで流れなくなったら終了
    if Ford_Fulkerson(0, N - 1):
        continue
    else:
        break
cost_aft = deepcopy(cost)
print(ans)
alta = deepcopy(S)

for key, value in cost_aft.items():
    if key == 0 or n * m < key:
        continue
    for k, v in value.items():
        if v == 0:
            sy, sx = change_rev(key)
            ey, ex = change2_rev(k)
            s1y = min(sy, ey)
            e1y = max(sy, ey)
            s1x = min(sx, ex)
            e1x = max(sx, ex)
            if sy == ey:
                alta[s1y][s1x] = '>'
                alta[e1y][e1x] = '<'
            else:
                alta[s1y][s1x] = 'v'
                alta[e1y][e1x] = '^'
for i in alta:
    print(''.join(i))

Submission status: Runtime Error

Solution code:
# thanks: https://atcoder.jp/contests/practice2/submissions/16784996

#!usr/bin/env python3
from collections import defaultdict, deque, Counter, OrderedDict
from bisect import bisect_left, bisect_right
from functools import reduce, lru_cache
from heapq import heappush, heappop, heapify

import itertools
import math, fractions
import sys, copy

def L(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline().rstrip())
def SL(): return list(sys.stdin.readline().rstrip())
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI1(): return [int(x) - 1 for x in sys.stdin.readline().split()]
def LS(): return [list(x) for x in sys.stdin.readline().split()]
def R(n): return [sys.stdin.readline().strip() for _ in range(n)]
def LR(n): return [L() for _ in range(n)]
def IR(n): return [I() for _ in range(n)]
def LIR(n): return [LI() for _ in range(n)]
def LIR1(n): return [LI1() for _ in range(n)]
def SLR(n): return [SL() for _ in range(n)]
def LSR(n): return [LS() for _ in range(n)]

def perm(n, r): return math.factorial(n) // math.factorial(r)
def comb(n, r): return math.factorial(n) // (math.factorial(r) * math.factorial(n-r))

def make_list(n, *args, default=0): return [make_list(*args, default=default) for _ in range(n)] if args else [default for _ in range(n)]

dire = [[1, 0], [0, 1], [-1, 0], [0, -1]]
dire8 = [[1, 0], [1, 1], [0, 1], [-1, 1], [-1, 0], [-1, -1], [0, -1], [1, -1]]
alphabets = "abcdefghijklmnopqrstuvwxyz"
ALPHABETS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
MOD = 1000000007
INF = float("inf")

sys.setrecursionlimit(1000000)

class MaxFlowGraph:
    def __init__(self, N):
        self.N = N
        self.graph = [[] for _ in range(N)]
        self.paths = []
        self.capacities = [dict() for _ in range(N)]

    def add_edge(self, v, w, cap=1):
        self.graph[v].append(w)
        self.graph[w].append(v)
        self.capacities[v][w] = cap
        self.capacities[w][v] = 0

    def dinic_bfs(self, s, t):
        self.level = [-1] * self.N
        q = deque([s])
        self.level[s] = 0
        while q:
            v = q.popleft()
            for w, cap in self.capacities[v].items():
                if cap and self.level[w] == -1:
                    self.level[w] = self.level[v] + 1
                    if w == t: return True
                    q.append(w)
        return False

    def dinic_dfs(self, s, t, limit):
        st = [t]
        while st:
            v = st[-1]
            if v == s: break
            #vから行ける全ての頂点について
            while self.it[v] < len(self.graph[v]):
                # w -> v の cap
                w = self.graph[v][self.it[v]]
                cap = self.capacities[w][v]
                if cap and self.level[w] != -1 and self.level[v] > self.level[w]:
                    st.append(w)
                    break
                self.it[v] += 1
            else:
                st.pop()
                self.level[v] = self.N
        else: return 0

        flow = min(limit, min(self.capacities[st[i + 1]][st[i]] for i in range(len(st) - 2)))
        for i in range(len(st) - 1):
            self.capacities[st[i]][st[i+1]] += flow
            self.capacities[st[i+1]][st[i]] -= flow
        self.paths.append(st)
        return flow

    def dinic_flow(self, s, t, flow_limit=18446744073709551615):
        flow = 0
        while flow < flow_limit and self.dinic_bfs(s, t):
            self.it = [0]*self.N
            while flow < flow_limit:
                f = self.dinic_dfs(s, t, flow_limit - flow)
                if not f: break
                flow += f
        return flow

    def min_cut(self, s):
        visited = [False]*self.N
        q = [s]
        while q:
            v = q.pop()
            visited[v] = True
            for w, cap in self.capacities[v].items():
                if cap and not visited[w]:
                    q.append(w)

def main():
    N, M = LI()
    S = SLR(N)
    g = MaxFlowGraph(N*M+2)

    s = N*M
    t = N*M+1

    # 偶数はblack, 奇数はwhiteとして市松模様に塗る、二部グラフの最大マッチング問題
    # s -> black -> white -> t の辺を張って最大流を求める
    for y in range(N):
        for x in range(M):
            # black
            if (y+x) % 2 == 0:
                g.add_edge(s, M*y+x)
                for dy, dx in [[1, 0], [0, 1]]:
                    ny, nx = y + dy, x + dx
                    if 0 <= ny < N and 0 <= nx < M and S[y][x] == "." and S[ny][nx] == ".":
                        g.add_edge(M*y+x, M*ny+nx)
            # white
            else:
                g.add_edge(M*y+x, t)
                for dy, dx in [[1, 0], [0, 1]]:
                    ny, nx = y + dy, x + dx
                    if 0 <= ny < N and 0 <= nx < M and S[y][x] == "." and S[ny][nx] == ".":
                        g.add_edge(M*ny+nx, M*y+x)

    print(g.dinic_flow(s, t))
    print(paths)
    for path in g.paths:
        u, v = path[1:-1]
        uy, ux = divmod(u, M)
        vy, vx = divmod(v, M)
        if uy - 1 == vy:
            S[uy][ux], S[vy][vx] = "^", "v"
        elif uy + 1 == vy:
            S[uy][ux], S[vy][vx] = "v", "^"
        elif ux + 1 == vx:
            S[uy][ux], S[vy][vx] = ">", "<"
        elif ux - 1 == vx:
            S[uy][ux], S[vy][vx] = "<", ">"
    for p in S:
        print("".join(p))

    for p in S:
        print("".join(p))



if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
# thanks: https://atcoder.jp/contests/practice2/submissions/16784996

#!usr/bin/env python3
from collections import defaultdict, deque, Counter, OrderedDict
from bisect import bisect_left, bisect_right
from functools import reduce, lru_cache
from heapq import heappush, heappop, heapify

import itertools
import math, fractions
import sys, copy

def L(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline().rstrip())
def SL(): return list(sys.stdin.readline().rstrip())
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI1(): return [int(x) - 1 for x in sys.stdin.readline().split()]
def LS(): return [list(x) for x in sys.stdin.readline().split()]
def R(n): return [sys.stdin.readline().strip() for _ in range(n)]
def LR(n): return [L() for _ in range(n)]
def IR(n): return [I() for _ in range(n)]
def LIR(n): return [LI() for _ in range(n)]
def LIR1(n): return [LI1() for _ in range(n)]
def SLR(n): return [SL() for _ in range(n)]
def LSR(n): return [LS() for _ in range(n)]

def perm(n, r): return math.factorial(n) // math.factorial(r)
def comb(n, r): return math.factorial(n) // (math.factorial(r) * math.factorial(n-r))

def make_list(n, *args, default=0): return [make_list(*args, default=default) for _ in range(n)] if args else [default for _ in range(n)]

dire = [[1, 0], [0, 1], [-1, 0], [0, -1]]
dire8 = [[1, 0], [1, 1], [0, 1], [-1, 1], [-1, 0], [-1, -1], [0, -1], [1, -1]]
alphabets = "abcdefghijklmnopqrstuvwxyz"
ALPHABETS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
MOD = 1000000007
INF = float("inf")

sys.setrecursionlimit(1000000)

class MaxFlowGraph:
    def __init__(self, N):
        self.N = N
        self.graph = [[] for _ in range(N)]
        self.paths = []
        self.capacities = [dict() for _ in range(N)]

    def add_edge(self, v, w, cap=1):
        self.graph[v].append(w)
        self.graph[w].append(v)
        self.capacities[v][w] = cap
        self.capacities[w][v] = 0

    def dinic_bfs(self, s, t):
        self.level = [-1] * self.N
        q = deque([s])
        self.level[s] = 0
        while q:
            v = q.popleft()
            for w, cap in self.capacities[v].items():
                if cap and self.level[w] == -1:
                    self.level[w] = self.level[v] + 1
                    if w == t: return True
                    q.append(w)
        return False

    def dinic_dfs(self, s, t, limit):
        st = [t]
        while st:
            v = st[-1]
            if v == s: break
            #vから行ける全ての頂点について
            while self.it[v] < len(self.graph[v]):
                # w -> v の cap
                w = self.graph[v][self.it[v]]
                cap = self.capacities[w][v]
                if cap and self.level[w] != -1 and self.level[v] > self.level[w]:
                    st.append(w)
                    break
                self.it[v] += 1
            else:
                st.pop()
                self.level[v] = self.N
        else: return 0

        flow = min(limit, min(self.capacities[st[i + 1]][st[i]] for i in range(len(st) - 2)))
        for i in range(len(st) - 1):
            self.capacities[st[i]][st[i+1]] += flow
            self.capacities[st[i+1]][st[i]] -= flow
        self.paths.append(st)
        return flow

    def dinic_flow(self, s, t, flow_limit=18446744073709551615):
        flow = 0
        while flow < flow_limit and self.dinic_bfs(s, t):
            self.it = [0]*self.N
            while flow < flow_limit:
                f = self.dinic_dfs(s, t, flow_limit - flow)
                if not f: break
                flow += f
        return flow

    def min_cut(self, s):
        visited = [False]*self.N
        q = [s]
        while q:
            v = q.pop()
            visited[v] = True
            for w, cap in self.capacities[v].items():
                if cap and not visited[w]:
                    q.append(w)

def main():
    N, M = LI()
    S = SLR(N)
    g = MaxFlowGraph(N*M+2)

    s = N*M
    t = N*M+1

    # 偶数はblack, 奇数はwhiteとして市松模様に塗る、二部グラフの最大マッチング問題
    # s -> black -> white -> t の辺を張って最大流を求める
    for y in range(N):
        for x in range(M):
            # black
            if (y+x) % 2 == 0:
                g.add_edge(s, M*y+x)
                for dy, dx in [[1, 0], [0, 1]]:
                    ny, nx = y + dy, x + dx
                    if 0 <= ny < N and 0 <= nx < M and S[y][x] == "." and S[ny][nx] == ".":
                        g.add_edge(M*y+x, M*ny+nx)
            # white
            else:
                g.add_edge(M*y+x, t)
                for dy, dx in [[1, 0], [0, 1]]:
                    ny, nx = y + dy, x + dx
                    if 0 <= ny < N and 0 <= nx < M and S[y][x] == "." and S[ny][nx] == ".":
                        g.add_edge(M*ny+nx, M*y+x)

    print(g.dinic_flow(s, t))

    for path in g.paths:
        u, v = path[1:-1]
        uy, ux = divmod(u, M)
        vy, vx = divmod(v, M)
        if uy - 1 == vy:
            S[uy][ux], S[vy][vx] = "^", "v"
        elif uy + 1 == vy:
            S[uy][ux], S[vy][vx] = "v", "^"
        elif ux + 1 == vx:
            S[uy][ux], S[vy][vx] = ">", "<"
        elif ux - 1 == vx:
            S[uy][ux], S[vy][vx] = "<", ">"
    for p in S:
        print("".join(p))




if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
# thanks: https://atcoder.jp/contests/practice2/submissions/16784996

#!usr/bin/env python3
from collections import defaultdict, deque, Counter, OrderedDict
from bisect import bisect_left, bisect_right
from functools import reduce, lru_cache
from heapq import heappush, heappop, heapify

import itertools
import math, fractions
import sys, copy

def L(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline().rstrip())
def SL(): return list(sys.stdin.readline().rstrip())
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI1(): return [int(x) - 1 for x in sys.stdin.readline().split()]
def LS(): return [list(x) for x in sys.stdin.readline().split()]
def R(n): return [sys.stdin.readline().strip() for _ in range(n)]
def LR(n): return [L() for _ in range(n)]
def IR(n): return [I() for _ in range(n)]
def LIR(n): return [LI() for _ in range(n)]
def LIR1(n): return [LI1() for _ in range(n)]
def SLR(n): return [SL() for _ in range(n)]
def LSR(n): return [LS() for _ in range(n)]

def perm(n, r): return math.factorial(n) // math.factorial(r)
def comb(n, r): return math.factorial(n) // (math.factorial(r) * math.factorial(n-r))

def make_list(n, *args, default=0): return [make_list(*args, default=default) for _ in range(n)] if args else [default for _ in range(n)]

dire = [[1, 0], [0, 1], [-1, 0], [0, -1]]
dire8 = [[1, 0], [1, 1], [0, 1], [-1, 1], [-1, 0], [-1, -1], [0, -1], [1, -1]]
alphabets = "abcdefghijklmnopqrstuvwxyz"
ALPHABETS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
MOD = 1000000007
INF = float("inf")

sys.setrecursionlimit(1000000)

class MaxFlowGraph:
    def __init__(self, N):
        self.N = N
        self.graph = [[] for _ in range(N)]
        self.capacities = [dict() for _ in range(N)]

    def add_edge(self, v, w, cap):
        self.graph[v].append(w)
        self.graph[w].append(v)
        self.capacities[v][w] = cap
        self.capacities[w][v] = 0

    def bfs(self, s, t):
        self.level = [-1] * self.N
        q = [s]
        self.level[s] = 0
        while q:
            nq = []
            for v in q:
                for w, cap in self.capacities[v].items():
                    if cap and self.level[w] == -1:
                        self.level[w] = self.level[v] + 1
                        if w == t:
                            return True
                        nq.append(w)
            q = nq
        return False

    def dfs(self, s, t, up):
        st = [t]
        while st:
            v = st[-1]
            if v == s:
                flow = up
                for i in range(len(st) - 2):
                    if flow > self.capacities[st[i + 1]][st[i]]:
                        flow = self.capacities[st[i+1]][st[i]]
                for i in range(len(st) - 1):
                    self.capacities[st[i]][st[i+1]] += flow
                    self.capacities[st[i+1]][st[i]] -= flow
                return flow
            while self.it[v] < len(self.graph[v]):
                w = self.graph[v][self.it[v]]
                cap = self.capacities[w][v]
                if cap and self.level[w] != -1:
                    if self.level[v] > self.level[w]:
                        st.append(w)
                        break
                self.it[v] += 1
            else:
                st.pop()
                self.level[v] = self.N
        return 0

    def flow(self, s, t, flow_limit=18446744073709551615):
        flow = 0
        while flow < flow_limit and self.bfs(s, t):
            self.it = [0]*self.N
            while flow < flow_limit:
                f = self.dfs(s, t, flow_limit - flow)
                if not f:
                    break
                flow += f
        return flow

    def min_cut(self, s):
        visited = [False]*self.N
        q = [s]
        while q:
            v = q.pop()
            visited[v] = True
            for w, cap in self.capacities[v].items():
                if cap and not visited[w]:
                    q.append(w)

def main():
    N, M = LI()
    S = SLR(N)
    g = MaxFlowGraph(N*M+2)

    s = N*M
    t = N*M+1

    # 偶数はblack, 奇数はwhiteとして市松模様に塗る、二部グラフの最大マッチング問題
    # s -> black -> white -> t の辺を張って最大流を求める
    # for y in range(N):
    #     for x in range(M):
    #         # black
    #         if (y+x) % 2 == 0:
    #             g.add_edge(s, M*y+x)
    #             for dy, dx in [[1, 0], [0, 1]]:
    #                 ny, nx = y + dy, x + dx
    #                 if 0 <= ny < N and 0 <= nx < M and S[y][x] == "." and S[ny][nx] == ".":
    #                     g.add_edge(M*y+x, M*ny+nx)
    #         # white
    #         else:
    #             g.add_edge(M*y+x, t)
    #             for dy, dx in [[1, 0], [0, 1]]:
    #                 ny, nx = y + dy, x + dx
    #                 if 0 <= ny < N and 0 <= nx < M and S[y][x] == "." and S[ny][nx] == ".":
    #                     g.add_edge(M*ny+nx, M*y+x)


    for i in range(N):
        for j in range(M):
            if (i+j) % 2 == 0:
                g.add_edge(s, M*i+j, 1)
            else:
                g.add_edge(M*i+j, t, 1)

    for i in range(N):
        for j in range(M):
            if j+1 < M and S[i][j] == "." and S[i][j+1] == ".":
                u, v = M*i+j, M*i+j+1
                if (i+j) % 2 == 1:
                    u, v = v, u
                g.add_edge(u, v, 1)
            if i+1 < N and S[i][j] == "." and S[i + 1][j] == ".":
                u, v = M*i+j, M*(i+1)+j
                if (i+j) % 2 == 1:
                    u, v = v, u
                g.add_edge(u, v, 1)

    print(g.flow(s, t))

    # blackから考える
    for u in range(0, N*M+1, 2):
        uy, ux = divmod(u, M)

        for v, cap in g.capacities[u].items():
            if cap != 0: continue
            vy, vx = divmod(v, M)
            if v != s and v != t:
                if uy - 1 == vy:
                    S[uy][ux], S[vy][vx] = "^", "v"
                elif uy + 1 == vy:
                    S[uy][ux], S[vy][vx] = "v", "^"
                elif ux + 1 == vx:
                    S[uy][ux], S[vy][vx] = ">", "<"
                elif ux - 1 == vx:
                    S[uy][ux], S[vy][vx] = "<", ">"

    for p in S:
        print("".join(p))



if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
import networkx as nx

n, m = map(int, input().split())


def calc(i, j):  # 0<=i<n, 0<=j<m
    return i * m + j


def inv(num):
    return num // m, num % m


S = [list(input()) for _ in range(n)]
start = n * m
goal = start + 1
G = nx.Graph()
di = [1, 0, -1, 0]
dj = [0, 1, 0, -1]
for num in range(n * m):
    i, j = inv(num)
    if S[i][j] == "#":
        continue
    if num % 2:
        G.add_edge(start, num, capacity=1)
    else:
        G.add_edge(num, goal, capacity=1)
    for k in range(4):
        ni = i + di[k]
        nj = j + dj[k]
        if 0 <= ni < n and 0 <= nj < n:
            if S[ni][nj] == ".":
                G.add_edge(num, calc(ni, nj), capacity=1)

flow_value, flow_dict = nx.maximum_flow(G, start, goal)

for num in range(n * m):
    i, j = inv(num)
    if num in flow_dict:
        for edge, val in flow_dict[num].items():
            if edge == goal:
                continue
            if val:
                ni, nj = inv(edge)
                if ni < i:
                    i, ni = ni, i
                if nj < j:
                    j, nj = nj, j
                if i == ni:  # nj-j==1
                    S[i][j] = ">"
                    S[ni][nj] = "<"
                if j == nj:  # ni-i==1
                    S[i][j] = "v"
                    S[ni][nj] = "^"

print(flow_value)
for i in range(n):
    print("".join(S[i]))

Submission status: Runtime Error

Solution code:
#!usr/bin/env python3
from collections import defaultdict, deque, Counter, OrderedDict
from bisect import bisect_left, bisect_right
from functools import reduce, lru_cache
from heapq import heappush, heappop, heapify

import itertools
import math, fractions
import sys, copy

def L(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline().rstrip())
def SL(): return list(sys.stdin.readline().rstrip())
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI1(): return [int(x) - 1 for x in sys.stdin.readline().split()]
def LS(): return [list(x) for x in sys.stdin.readline().split()]
def R(n): return [sys.stdin.readline().strip() for _ in range(n)]
def LR(n): return [L() for _ in range(n)]
def IR(n): return [I() for _ in range(n)]
def LIR(n): return [LI() for _ in range(n)]
def LIR1(n): return [LI1() for _ in range(n)]
def SLR(n): return [SL() for _ in range(n)]
def LSR(n): return [LS() for _ in range(n)]

def perm(n, r): return math.factorial(n) // math.factorial(r)
def comb(n, r): return math.factorial(n) // (math.factorial(r) * math.factorial(n-r))

def make_list(n, *args, default=0): return [make_list(*args, default=default) for _ in range(n)] if args else [default for _ in range(n)]

dire = [[1, 0], [0, 1], [-1, 0], [0, -1]]
dire8 = [[1, 0], [1, 1], [0, 1], [-1, 1], [-1, 0], [-1, -1], [0, -1], [1, -1]]
alphabets = "abcdefghijklmnopqrstuvwxyz"
ALPHABETS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
MOD = 1000000007
INF = float("inf")

sys.setrecursionlimit(1000000)

class MaxFlowGraph:
    def __init__(self, N):
        self.N = N
        self.graph = [[] for _ in range(N)]
        self.capacities = [defaultdict(int) for _ in range(N)]

    def add_edge(self, v, w, cap=1):
        self.graph[v].append(w)
        self.graph[w].append(v)
        self.capacities[v][w] = cap
        self.capacities[w][v] = 0

    def flow(self, s, t, flow_limit=0XFFFFFFFFFFFFFFF):
        flow = 0
        while flow < flow_limit and self.bfs(s, t):
            while flow < flow_limit:
                f = self.dfs(s, t, flow_limit - flow)
                if not f:
                    break
                flow += f
        return flow

    def bfs(self, s, t):
        self.level = [-1] * self.N
        q = [s]
        self.level[s] = 0
        while q:
            nq = []
            for v in q:
                for w, cap in self.capacities[v].items():
                    if cap and self.level[w] == -1:
                        self.level[w] = self.level[v] + 1
                        if w == t:
                            return True
                        nq.append(w)
            q = nq
        return False

    def dfs(self, s, t, up):
        self.it = [0]*self.N
        st = [t]
        while st:
            v = st[-1]
            if v == s:
                flow = up
                for i in range(len(st) - 2):
                    if flow > self.capacities[st[i + 1]][st[i]]:
                        flow = self.capacities[st[i+1]][st[i]]
                for i in range(len(st) - 1):
                    self.capacities[st[i]][st[i+1]] += flow
                    self.capacities[st[i+1]][st[i]] -= flow
                return flow
            while self.it[v] < len(self.graph[v]):
                w = self.graph[v][self.it[v]]
                cap = self.capacities[w][v]
                if cap and self.level[w] != -1:
                    if self.level[v] > self.level[w]:
                        st.append(w)
                        break
                self.it[v] += 1
            else:
                st.pop()
                self.level[v] = self.N
        return 0

    def min_cut(self, s):
        visited = [False]*self.N
        q = [s]
        while q:
            v = q.pop()
            visited[v] = True
            for w, cap in self.capacities[v].items():
                if cap and not visited[w]:
                    q.append(w)


def main():
    N, M = LI()
    S = SLR(N)
    g = MaxFlowGraph(N*M+2)

    s = N*M
    t = N*M+1

    # 偶数はblack, 奇数はwhiteとして市松模様に塗る、二部グラフの最大マッチング問題
    # s -> black -> white -> t の辺を張って最大流を求める
    for y in range(N):
        for x in range(M):
            # black
            if (y+x) % 2 == 0:
                g.add_edge(s, M*y+x)
                for dy, dx in [[1, 0], [0, 1]]:
                    ny, nx = y + dy, x + dx
                    if 0 <= ny < M and 0 <= nx < M and S[y][x] == "." and S[ny][nx] == ".":
                        g.add_edge(M*y+x, M*ny+nx)
            # white
            else:
                g.add_edge(M*y+x, t)
                for dy, dx in [[1, 0], [0, 1]]:
                    ny, nx = y + dy, x + dx
                    if 0 <= ny < M and 0 <= nx < M and S[y][x] == "." and S[ny][nx] == ".":
                        g.add_edge(M*ny+nx, M*y+x)

    print(g.flow(s, t))

    # blackから考える
    for u in range(0, N*M, 2):
        uy, ux = divmod(u, M)

        for v, cap in g.capacities[u].items():
            if cap != 0: continue
            vy, vx = divmod(v, M)
            if v != s and v != t:
                if uy - 1 == vy:
                    S[uy][ux], S[vy][vx] = "^", "v"
                elif uy + 1 == vy:
                    S[uy][ux], S[vy][vx] = "v", "^"
                elif ux + 1 == vx:
                    S[uy][ux], S[vy][vx] = ">", "<"
                elif ux - 1 == vx:
                    S[uy][ux], S[vy][vx] = "<", ">"

    for p in S:
        print("".join(p))



if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
import networkx as nx

n, m = map(int, input().split())


def calc(i, j):  # 0<=i<n, 0<=j<m
    return i * m + j


def inv(num):
    return num // m, num % m


S = [list(input()) for _ in range(n)]
start = n * m
goal = start + 1
G = nx.Graph()
di = [1, 0, -1, 0]
dj = [0, 1, 0, -1]
for num in range(n * m):
    i, j = inv(num)
    if S[i][j] == "#":
        continue
    if num % 2:
        G.add_edge(start, num, capacity=1)
    else:
        G.add_edge(num, goal, capacity=1)
    for k in range(4):
        ni = i + di[k]
        nj = j + dj[k]
        if 0 <= ni < n and 0 <= nj < n:
            if S[ni][nj] == ".":
                G.add_edge(num, calc(ni, nj), capacity=1)

flow_value, flow_dict = nx.maximum_flow(G, start, goal)

for num in range(n * m):
    i, j = inv(num)
    if S[i][j] == ".":
        if 0 <= j + 1 < m:
            if S[i][j + 1] == ".":
                if flow_dict[num][num + 1] or flow_dict[num + 1][num]:
                    S[i][j] = ">"
                    S[i][j + 1] = "<"
        if 0 <= i + 1 < n:
            if S[i + 1][j] == ".":
                if flow_dict[num][num + m] or flow_dict[num + m][num]:
                    S[i][j] = "v"
                    S[i + 1][j] = "^"

print(flow_value)
for i in range(n):
    print("".join(S[i]))