Problem:


Score : 400 points

Problem Statement

Consider a grid with H rows and W columns of squares. Let (r, c) denote the square at the r-th row from the top and the c-th column from the left.
Each square is painted black or white.

The grid is said to be good if and only if the following condition is satisfied:

From (1, 1), we can reach (H, W) by moving one square right or down repeatedly, while always being on a white square.

Note that (1, 1) and (H, W) must be white if the grid is good.

Your task is to make the grid good by repeating the operation below. Find the minimum number of operations needed to complete the task. It can be proved that you can always complete the task in a finite number of operations.

Choose four integers r_0, c_0, r_1, c_1(1 \leq r_0 \leq r_1 \leq H, 1 \leq c_0 \leq c_1 \leq W). For each pair r, c (r_0 \leq r \leq r_1, c_0 \leq c \leq c_1), invert the color of (r, c) - that is, from white to black and vice versa.

Constraints

2 \leq H, W \leq 100

Input

Input is given from Standard Input in the following format:

H W
s_{11} s_{12} \cdots s_{1W}
s_{21} s_{22} \cdots s_{2W}
 \vdots
s_{H1} s_{H2} \cdots s_{HW}

Here s_{rc} represents the color of (r, c) - # stands for black, and . stands for white.

Output

Print the minimum number of operations needed.

Sample Input 1

3 3
.##
.#.
##.

Sample Output 1

1

Do the operation with (r_0, c_0, r_1, c_1) = (2, 2, 2, 2) to change just the color of (2, 2), and we are done.

Sample Input 2

2 2
#.
.#

Sample Output 2

2

Sample Input 3

4 4
..##
#...
###.
###.

Sample Output 3

0

No operation may be needed.

Sample Input 4

5 5
.#.#.
#.#.#
.#.#.
#.#.#
.#.#.

Sample Output 4

4



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


Sample output:
1

Submission status: Accepted

Solution code:
h,w=map(int,input().split())
l=[list(input()) for i in range(h)]
ans=[[0 for i in range(w)] for j in range(h)]
if l[0][0]=='#':
  ans[0][0]=1
for i in range(h):
  for j in range(w):
    if i!=0 or j!=0:
      if i!=0 and j!=0:
        if l[i][j]=='#' and l[i-1][j]=='.':
          x=ans[i-1][j]+1
        else:
          x=ans[i-1][j]
        if l[i][j]=='#' and l[i][j-1]=='.':
          y=ans[i][j-1]+1
        else:
          y=ans[i][j-1]
        ans[i][j]=min(x,y)
      elif i==0 and j!=0:
        if l[i][j]=='#' and l[i][j-1]=='.':
          y=ans[i][j-1]+1
        else:
          y=ans[i][j-1]
        ans[i][j]=y
      else:
        if l[i][j]=='#' and l[i-1][j]=='.':
          x=ans[i-1][j]+1
        else:
          x=ans[i-1][j]
        ans[i][j]=x
print(ans[h-1][w-1])

Submission status: Accepted

Solution code:
#  --*-coding:utf-8-*--

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


S0 = '.' + '#'*(W-1)
X0 = [MAX]*W
X0[0] = 0

for _ in range(H):
    S = input()
    X = [None]*W

    for i in range(W):
        sc1 = MAX
        sc2 = MAX

        if i > 0:
            sc1 = X[i-1] + (1 if S[i-1] == '.' and S[i] == '#' else 0)

        sc2 = X0[i] + (1 if S0[i] == '.' and S[i] == '#' else 0)

        X[i] = min(sc1, sc2)

    X0 = X
    S0 = S

print(X0[-1])

Submission status: Accepted

Solution code:
#!/usr/bin/env python3

import sys
import math
from bisect import bisect_right as br
from bisect import bisect_left as bl
sys.setrecursionlimit(2147483647)
from heapq import heappush, heappop,heappushpop
from collections import defaultdict
from itertools import accumulate
from collections import Counter
from collections import deque
from operator import itemgetter
from itertools import permutations
mod = 10**9 + 7
inf = float('inf')
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))

H,W = LI()
s = [input() for _ in range(H)]
dx,dy = [1,0],[0,1]
dp = [[inf]*W for _ in range(H)]


if s[0][0] == '#':
    dp[0][0] = 1
else:
    dp[0][0] = 0

h = []
heappush(h, (dp[0][0],0,0))
while h:
    d,y,x = heappop(h)
    for i in range(2):
        nx,ny = x + dx[i], y +dy[i]
        if 0 <= nx < W and 0 <= ny < H:
            if s[ny][nx] == '#' and s[y][x] == '#' and dp[ny][nx] > d:
                dp[ny][nx] = d
                heappush(h,(dp[ny][nx],ny,nx))
            elif s[ny][nx] == '#' and  s[y][x] == '.' and dp[ny][nx] > d+1:
                dp[ny][nx] = d + 1
                heappush(h, (dp[ny][nx],ny,nx))
            elif s[ny][nx] == '.' and dp[ny][nx] > d:
                dp[ny][nx] = d
                heappush(h,(dp[ny][nx],ny,nx))
print(dp[-1][-1])

Submission status: Accepted

Solution code:
H, W = [int(s) for s in input().split()]
map = []
for i in range(H):
    map.append(input())

op = [[0 for i in range(W)] for j in range(H)]
op[0][0] = int(map[0][0] == '#')
for i in range(1, W):
    op[0][i] = op[0][i-1] + int(map[0][i] == '#' and map[0][i-1] == '.')
for i in range(1, H):
    op[i][0] = op[i-1][0] + int(map[i][0] == '#' and map[i-1][0] == '.')
for i in range(1, H):
    for j in range(1, W):
        op[i][j] = min(op[i-1][j] + int(map[i][j] == '#' and map[i-1][j] == '.'),
                       op[i][j-1] + int(map[i][j] == '#' and map[i][j-1] == '.'))
print(op[H-1][W-1])

Submission status: Accepted

Solution code:

def I(): return int(input())
def MI(): return map(int, input().split())
def LI(): return list(map(int, input().split()))

def main():
    mod=10**9+7
    H,W=MI()
    s=[[] for _ in range(H+2)]
    s[0]="#"*(W+2)
    for i in range(H):
        s[i+1]="#"+input()+"#"
    s[-1]="#"*(W+2)
            
            
    dx=[0,1]
    dy=[1,0]
    
    inf=10**7
    #dp[i][j]はますi,jにたどり着くときの最小コスト，コストは色が変わった数
    dp=[[inf]*(W+2) for _ in range(H+2)]
    
    if s[1][1]==".":
        dp[1][1]=0
    else:
        dp[1][1]=1
        
    for i in range(1,H+1):
        for j in range(1,W+1):
            for k in range(2):
                ii=i+dx[k]
                jj=j+dy[k]
                if s[ii][jj]==s[i][j]:
                    a=0
                else:
                    a=1
                dp[ii][jj]=min(dp[ii][jj],dp[i][j]+a)
    
    print((dp[H][W]+1)//2)
    

main()

Submission status: Accepted

Solution code:
from collections import deque
t,*g=open(0)
h,w=map(int,t.split())
vis=[[1e9]*w for _ in range(h)]
vis[0][0]=int(g[0][0]=="#")
q=deque([(0,0,vis[0][0])])
while q:
	cy,cx,c=q.popleft()
	for ny,nx in ((cy+1,cx),(cy,cx+1)):
		cc=c
		if not (0<=ny<h and 0<=nx<w):
			continue
		if g[cy][cx]=="." and g[ny][nx]=="#":
			cc+=1
		if cc<vis[ny][nx]:
			vis[ny][nx]=cc
			q.append((ny,nx,cc))
#print(vis)
print(vis[-1][-1])

Submission status: Accepted

Solution code:
h,w = map(int, input().split())
l = [None]*h
for i in range(h):
    l[i] = list(input())


from collections import deque

def solve(x,y):
    dx = [1, 0]
    dy = [0, 1]

    start = [x, y]
    dist = [[10**3]*w for i in range(h)]
    dist[y][x] = 0
    Q = deque()
    Q.append([start,l[0][0]])
    mx = 0

    while Q:
        p,color = Q.popleft()
        for i in range(2):
            nx = p[0] + dx[i]
            ny = p[1] + dy[i]

            if 0 <= nx < w and 0 <= ny < h:
                if l[ny][nx]!=color:
                    cost=1
                else:
                    cost=0
                if dist[ny][nx] > dist[p[1]][p[0]] + cost:
                    Q.append([[nx, ny],l[ny][nx]])
                    dist[ny][nx] = dist[p[1]][p[0]] + cost
    return dist

dist=solve(0,0)
if l[0][0] == "#" or l[-1][-1]=="#":
    print(1+dist[-1][-1]//2)
else:
    print(dist[-1][-1]//2)

Submission status: Accepted

Solution code:
h, w = map(int, input().split())
A = [input() for i in range(h)]

dp = [[float("inf")]*w for _ in range(h)]
dp[0][0] = 0 if A[0][0] == "." else 1
for i in range(1, w):
    dp[0][i] = dp[0][i-1]+1 if A[0][i] == "#" and A[0][i-1] == "." else dp[0][i-1]
for i in range(1, h):
    dp[i][0] = dp[i-1][0]+1 if A[i][0] == "#" and A[i-1][0] == "." else dp[i-1][0]

for i in range(1, h):
    for j in range(1, w):
        left = dp[i][j-1]+1 if A[i][j] == "#" and A[i][j-1] == "." else dp[i][j-1]
        right = dp[i-1][j]+1 if A[i][j] == "#" and A[i-1][j] == "." else dp[i-1][j]
        # print(i, j, left, right)
        dp[i][j] = min(left, right)
# print(dp)

print(dp[-1][-1])

Submission status: Accepted

Solution code:
H, W = map(int, input().split())
MAX_VAL = 10**9
cost = [[MAX_VAL]*(W+1) for _ in range(H+1)]

field = ["#" * (W+1)]
for i in range(H):
    line = input()
    field.append("#" + line)

if field[1][1] == "#":
    cost[1][1] = 1
else:
    cost[1][1] = 0

for i in range(1, H+1):
    for j in range(1, W+1):
        if i * j == 1:
            continue

        if field[i][j] == ".":
            cost[i][j] = min(cost[i-1][j], cost[i][j-1])
        else:
            top_cost = cost[i-1][j]
            left_cost = cost[i][j-1]
            
            if field[i-1][j] == ".":
                top_cost += 1
            if field[i][j-1] == ".":
                left_cost += 1
            
            cost[i][j] = min(top_cost, left_cost)

print(cost[H][W])

Submission status: Accepted

Solution code:
H,W = map(int, input().split())
fields =  [list(input()) for i in range(H)]
# print(fields)

from collections import deque
cnts = [[1000] * W for i in range(H)]
q = deque()
q.append((0,0))
cnts[0][0] = 0
str_s = "."
mv = [(1,0),(0,1)]
while len(q) > 0:
    h,w = q.popleft()
    # mark = fields[h][w]
    for dh, dw in mv:
        if h + dh < H and w + dw < W:
            # print("upd",h,w,h+dh,w+dw,H,W)
            if fields[h][w] == fields[h+dh][w+dw]:
                upd = cnts[h][w] 
            else:
                if fields[h][w] == ".":
                    upd = cnts[h][w] + 1
                else:
                    upd = cnts[h][w]
            if cnts[h+dh][w+dw] > upd:
                cnts[h+dh][w+dw] = min(cnts[h+dh][w+dw],upd)
                q.append((h+dh,w+dw))

# print(cnts)

ans = cnts[H-1][W-1]
if fields[0][0] == "#":ans += 1
print(ans)

Submission status: Accepted

Solution code:
from heapq import heapify, heappop, heappush
from collections import defaultdict
inpl = lambda: list(map(int,input().split()))
H, W = inpl()
s = []
for h in range(H):
    s.append(input())

def dijkstra(start, goal):
    q = [(0, start)]
    done = set()
    minimum = defaultdict(lambda: None)

    while q:
        D, x = heappop(q)
        if x in done:
            continue
        elif x == goal:
            return D
        done.add(x)
        for y in {(x[0]+1,x[1]), (x[0],x[1]+1)}:
            if y[0] >= H or y[1] >= W:
                continue
            if not y in done:
                m = minimum[y]
                p = D + int(s[x[0]][x[1]] != s[y[0]][y[1]])
                if m is None or m > p:
                    heappush(q, (p, y))
                    minimum[y] = p

N = dijkstra((0,0), (H-1,W-1)) + 1
if s[0][0] == '.':
    print(N//2)
else:
    print((N+1)//2)

Submission status: Accepted

Solution code:
# coding: utf-8
from collections import deque


def solve(*args: str) -> str:
    h, w = map(int, args[0].split())
    black = [[True if s == '#' else False for s in S] for S in args[1:]]

    inf = 10**12
    counts = [[inf]*w for _ in range(h)]
    Q = deque([(0, 0, 0, False)])
    while Q:
        x, y, n, prev = Q.popleft()
        if h <= y or w <= x:
            continue

        if black[y][x]:
            if not prev:
                n += 1
                prev = True
        else:
            prev = False

        if n < counts[y][x]:
            counts[y][x] = n
            for dx, dy in [(1, 0), (0, 1)]:
                Q.append((x+dx, y+dy, n, prev))

    return str(counts[-1][-1])


if __name__ == "__main__":
    print(solve(*(open(0).read().splitlines())))

Submission status: Accepted

Solution code:
from collections import deque
h, w = map(int, input().split())

g = []
for _ in range(h):
    tmp = list(input())
    g.append(tmp)

dp = [[1000000 for _ in range(w)] for __ in range(h)]

dp[0][0] = 0
# q = deque([(0, 0)])

# while q:
#     x, y = q.popleft()
#     if x+1 < h:
#         if g[x+1][y] != g[x][y]:
#             dp[x+1][y] = min(dp[x+1][y], dp[x][y]+1)
#         else:
#             dp[x+1][y] = min(dp[x+1][y], dp[x][y])
#         q.append((x+1, y))
#     if y+1 < w:
#         if g[x][y+1] != g[x][y]:
#             dp[x][y+1] = min(dp[x][y+1], dp[x][y]+1)
#         else:
#             dp[x][y+1] = min(dp[x][y+1], dp[x][y])
#         q.append((x, y+1))

for i in range(h):
    for j in range(w):
        if i == 0 and j != 0:
            if g[i][j] != g[i][j-1]:
                dp[i][j] = dp[i][j-1] + 1
            else:
                dp[i][j] = dp[i][j-1]
        elif i != 0:
            if j == 0:
                if g[i][0] != g[i-1][0]:
                    dp[i][0] = dp[i-1][0] + 1
                else:
                    dp[i][0] = dp[i-1][0]
            else:
                if g[i][j] != g[i][j-1]:
                    dp[i][j] = min(dp[i][j], dp[i][j-1] + 1)
                else:
                    dp[i][j] = min(dp[i][j], dp[i][j-1])

                if g[i][j] != g[i-1][j]:
                    dp[i][j] = min(dp[i][j], dp[i-1][j]+1)
                else:
                    dp[i][j] = min(dp[i][j], dp[i-1][j])


if g[0][0] == '.' and g[h-1][w-1] == '.':
    print(dp[h-1][w-1]//2)
elif g[0][0] != g[h-1][w-1]:
    print((dp[h-1][w-1]+1)//2)
else:
    print(1 + (dp[h-1][w-1]//2))

Submission status: Accepted

Solution code:
from collections import deque
"""
-1 -> not visited
else -> step count
"""
def bfs(maze, visited, sh, sw, gh, gw):
    stack = deque([[sh, sw]])
    visited[sh][sw] = 1 if maze[sh][sw] == "#" else 0 # スタートの値
    while stack:
        h, w = stack.popleft()
#        # ゴールの条件
#        if h == gh and w == gw:
#            break
        for j, k in ([1, 0], [0, 1]):
            new_h, new_w = h+j, w+k
            if new_h < 0 or new_h >= H or \
                new_w < 0 or new_w >= W:
                    continue
            else:
              cost = 1 if maze[new_h][new_w] == "#" and maze[h][w] == "." else 0
              # visited[new]が未踏(-1)、もしくはコストが下がる  
              if visited[new_h][new_w] == -1 or visited[new_h][new_w] > visited[h][w] + cost:
                visited[new_h][new_w] = visited[h][w] + cost
                stack.append([new_h, new_w])
    
    return visited[gh][gw]

if __name__ == "__main__":
    H, W = map(int, input().split())
    maze = [list(input()) for _ in range(H)]

    visited = [[-1] * W for _ in range(H)]
    print(bfs(maze, visited, 0, 0, H-1, W-1))

Submission status: Accepted

Solution code:
import sys
stdin = sys.stdin

ni = lambda: int(ns())
na = lambda: list(map(int, stdin.readline().split()))
nn = lambda: list(stdin.readline().split())
ns = lambda: stdin.readline().rstrip()


h,w = na()
ss = []
for i in range(h):
    s = list(ns())
    ss.append(s)

dp = [[0]*w for i in range(h)]

for i in range(h):
    for j in range(w):
        if i == 0 and j == 0:
            if ss[i][j] == '#':
                dp[0][0] = 1
            continue
        a = i-1 if h>0 else 0
        b = j-1 if w>0 else 0
        c = 100000000 if j == 0 else dp[i][b]+1 if ss[i][j] == '#' and ss[i][j] != ss[i][b] else dp[i][b]
        d = 100000000 if i == 0 else dp[a][j]+1 if ss[i][j] == '#' and ss[i][j] != ss[a][j] else dp[a][j]
        dp[i][j] = min(c,d)

print(dp[h-1][w-1])

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline

H, W = map(int, input().split())
s = [input() for _ in range(H)]
dp = [[float('inf')] * W for _ in range(H)]
dp[0][0] = 1 if s[0][0] == '#' else 0
for i in range(H):
    for j in range(W):
        if i > 0:
            if s[i-1][j] == '.' and s[i][j] == '#':
                dp[i][j] = dp[i-1][j] + 1
            else:
                dp[i][j] = dp[i-1][j]
        if j > 0:
            if s[i][j-1] == '.' and s[i][j] == '#':
                dp[i][j] = min(dp[i][j], dp[i][j-1] + 1)
            else:
                dp[i][j] = min(dp[i][j], dp[i][j-1])
print(dp[-1][-1])

Submission status: Accepted

Solution code:
# import numpy as np
# import scipy as sp
# import sys
# input = sys.stdin.readline
# print(a,b,c,sep="") # 半角スペースなしで出力(abc)
# n=int(input())  #数値入力 「N」だけの入力のとき
# a,b=list(map(int, input().split()))  #複数数値入力　「A B」みたいなスペース空いた入力のとき
# a=list(map(int, input().split()))  #リスト入力 「a1 a2 a3 ...」みたいな配列のような入力のとき
# a=[int(input()) for _ in range (n)]  #リスト入力  改行でa1 ... anのとき
# s=[list(map(str,list(input()))) for i in range(h)]  # 文字列の二次元配列入力
# s = [list(map(int, input().split())) for i in range(n)] # 数値の二次元配列入力
# a = b[:], a = [x[:] for x in b] # deepcopy
# chr(ord('a') + 1) # chrのインクリメント
# s.sort(key=lambda x: x[1], reverse=False) # 2番目の要素で昇順にソート（Trueなら降順）
#　

h, w = list(map(int, input().split()))
s = [list(map(str, list(input()))) for i in range(h)]

INF = float("inf")
dp = [[INF]*w for _ in range(h)]

if s[0][0] == '#':
    dp[0][0] = 1
else:
    dp[0][0] = 0

for i in range(h):
    for j in range(w):
        if i+1 <= h-1:
            if s[i+1][j] == '.':
                dp[i+1][j] = min(dp[i+1][j], dp[i][j])
            else:
                if s[i][j] == '.':
                    dp[i+1][j] = min(dp[i+1][j], dp[i][j]+1)
                else:
                    dp[i+1][j] = min(dp[i+1][j], dp[i][j])

        if j+1 <= w-1:
            if s[i][j+1] == '.':
                dp[i][j+1] = min(dp[i][j+1], dp[i][j])
            else:
                if s[i][j] == '.':
                    dp[i][j+1] = min(dp[i][j+1], dp[i][j]+1)
                else:
                    dp[i][j+1] = min(dp[i][j+1], dp[i][j])

print(dp[-1][-1])

Submission status: Accepted

Solution code:
H,W = map(int,input().split())
S = [[c=="#" for c in input()] for _ in [0]*H]

d = [[H*W*10]*W for _ in [0]*H]
d[0][0] = int(S[0][0])

d0 = d[0]
S0 = S[0]
for j in range(1,W):
    if S0[j] and (not S0[j-1]):
        d0[j] = d0[j-1]+1
    else:
        d0[j] = d0[j-1]
for i in range(1,H):
    Si = S[i]
    di = d[i]
    if Si[0] and (not S[i-1][0]):
        di[0] = d[i-1][0] + 1
    else:
        di[0] = d[i-1][0]
    #
    for j in range(1,W):
        if Si[j] and (not S[i-1][j]):
            di[j] = d[i-1][j] + 1
        else:
            di[j] = d[i-1][j]
        if Si[j] and (not Si[j-1]):
            di[j] = min(di[j],di[j-1] + 1)
        else:
            di[j] = min(di[j],di[j-1])
print(d[-1][-1])

Submission status: Accepted

Solution code:
from functools import lru_cache


R, C = list(map(int, input().split()))
grid = []
for r in range(R):
    grid.append(list(input().rstrip()))


@lru_cache(maxsize=None)
def minDist(r, c):
    color = int(grid[r][c] == "#")

    best = float("inf")
    if r == 0 and c == 0:
        return color
    if r >= 1:
        best = min(
            best,
            int(grid[r][c] != grid[r - 1][c] and color)
            + minDist(r - 1, c),
        )
    if c >= 1:
        best = min(
            best,
            int(grid[r][c] != grid[r][c - 1] and color)
            + minDist(r, c - 1),
        )
    return best


print(minDist(R - 1, C - 1))

Submission status: Accepted

Solution code:
import math
H, W = map(int, input().split())
M = [input() for _ in range(H)]

INF = float('inf')
D = [[INF]*W for _ in range(H)]
D[0][0] = 0 if M[0][0] == '.' else 1

q = set([(0, 0)])

while q:
    nq = set()
    for y, x in q:
        d = D[y][x]
        m = M[y][x]
        if x < W-1:
            t = d if M[y][x+1] == m else d+1
            D[y][x+1] = min(D[y][x+1], t)
            nq.add((y, x+1))
        if y < H-1:
            t = d if M[y+1][x] == m else d+1
            D[y+1][x] = min(D[y+1][x], t)
            nq.add((y+1, x))
    q = nq

print(math.ceil(D[H-1][W-1] / 2))

Submission status: Accepted

Solution code:
H,W = list(map(int,input().split()))

grid = [['_']*(W+2)]
for i in range(H):
    grid.append(list('_' + input() + '_'))
grid.append(['_']*(W+2))

dp = [[float('inf')]*(W+2) for i in range(H+2)]
dp[0][1] = 0
for c in range(1,H+1):
    for r in range(1,W+1):
        if grid[c][r] == '#':
            left = dp[c][r-1]+1 if grid[c][r-1] != '#' else dp[c][r-1]
            up = dp[c-1][r]+1 if grid[c-1][r] != '#' else dp[c-1][r]
            dp[c][r] = min(left,up)
        else:
            dp[c][r] = min(dp[c][r-1],dp[c-1][r])

print(dp[H][W])

Submission status: Accepted

Solution code:
from heapq import heappop, heappush, heapify

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

dx = [1,0]
dy = [0,1]

res = 1

heap = [(1, 0, 0)]
heapify(heap)
visited = [[0 for j in range(W)] for i in range(H)]
visited[0][0] = 1

while heap:
    c, x, y = heappop(heap)
    for i in range(2):
        nx, ny = x + dx[i], y + dy[i]
        if not (0 <= nx < H and 0 <= ny < W):
            continue
        if visited[nx][ny]:
            continue
        if S[x][y] == S[nx][ny]:
            visited[nx][ny] = c
            heappush(heap, (c, nx, ny))
        else:
            visited[nx][ny] = c + 1
            heappush(heap, (c + 1, nx, ny))

if S[0][0] == '#':
    print((visited[-1][-1]+1)//2)
else:
    print(visited[-1][-1]//2)

Submission status: Accepted

Solution code:
import sys
from collections import deque
imput = sys.stdin.readline

h, w = map(int, input().split())
s = []
for _ in range(h):
    s.append(input().rstrip('\n'))

ans = h + w
memo = [[h + w for i in range(w)] for j in range(h)]

def bfs(cur, pre, cnt):
    global ans
    stack = deque([[cur, pre, cnt]])
    while stack:
        cur, pre, cnt = stack.popleft()
        r, c = cur
        col = s[r][c]
        if col != pre:
            cnt += 1
        if memo[r][c] > cnt:
            memo[r][c] = cnt
            if r == h-1 and c == w-1:
                ans = min(ans, cnt)
            next = [[r+1, c], [r, c+1]]
            for r2, c2 in next:
                if r2 < h and c2 < w:
                    stack.append([[r2, c2], col, cnt])

bfs([0, 0], '.', 0)

print((ans+1)//2)

Submission status: Accepted

Solution code:
import numpy as np
from scipy.sparse.csgraph import shortest_path, floyd_warshall, dijkstra, bellman_ford, johnson
from scipy.sparse import csr_matrix, lil_matrix

H, W = map(int, input().split())
# H, W = 2, 2
s = []
for _ in range(H):
    s.append(input())
# s = [func() for _ in range(H)]
# print('\n'.join(s))

def co_num(h, w):
    return h * W + w

row = []
col = []
dist = []
for h in range(H):
    for w in range(W):
#         if h != 0:
#             row.append(co_num(h, w))
#             col.append(co_num(h-1, w))
#             dist.append(0 if s[h-1][w] == s[h][w] else 1)
#         if w != 0:
#             row.append(co_num(h, w))
#             col.append(co_num(h, w-1))
#             dist.append(0 if s[h][w-1] == s[h][w] else 1)
        if h != H-1:
            row.append(co_num(h, w))
            col.append(co_num(h+1, w))
            dist.append(0 if s[h+1][w] == s[h][w] else 1)
        if w != W-1:
            row.append(co_num(h, w))
            col.append(co_num(h, w+1))
            dist.append(0 if s[h][w+1] == s[h][w] else 1)

d = int(dijkstra(csr_matrix((dist, (row, col)), shape=[H*W, H*W]), directed=True, indices=0)[H*W-1])

if s[0][0] == '.' and s[-1][-1] == '.':
    print(d // 2)
elif s[0][0] == '#' and s[-1][-1] == '#':
    print(d // 2 + 1)
else:
    print(d // 2 + 1)

Submission status: Accepted

Solution code:
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians
from itertools import accumulate, permutations, combinations, product
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left
from fractions import gcd
from heapq import heappush, heappop
from functools import reduce
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def ZIP(n): return zip(*(MAP() for _ in range(n)))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7

def main():
    H, W = MAP()
    dx = [1, 0]
    dy = [0, 1]
    s = [input() for _ in range(H)]

    start = (0, 0)

    q = deque()
    q.append(start)

    cost = [[INF]*W for _ in range(H)]
    if s[0][0] == "#":
        cost[0][0] = 1
    else:
        cost[0][0] = 0
    while q:
        i, j = q.popleft()
        for k in range(2):
            y = i + dy[k]
            x = j + dx[k]
            if y < 0 or y > H-1 or x < 0 or x > W-1:
                continue
            if s[i][j] == "." and s[y][x] == "#":  # コストが増える
                if cost[y][x] > cost[i][j] + 1:
                    cost[y][x] = cost[i][j] + 1
                    q.append((y, x))
            elif s[i][j] == "#" and s[y][x] == "#":
                if cost[y][x] > cost[i][j]: 
                    cost[y][x] = cost[i][j]
                    q.append((y, x))
            elif s[i][j] == "." and s[y][x] == ".":
                if cost[y][x] > cost[i][j]:
                    cost[y][x] = cost[i][j]
                    q.append((y, x))
            else:  # # -> .
                if cost[y][x] > cost[i][j]:
                    cost[y][x] = cost[i][j]
                    q.append((y, x))
    # print(cost)
    print(cost[H-1][W-1])

 

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
import sys
input = sys.stdin.readline
from collections import deque

h, w = map(int, input().split())
field = []
for _ in range(h):
    line = input().rstrip()
    field.append(line)

dp = [[-1] * w for _ in range(h)]

st = deque() 
if field[h-1][w-1] == ".":
    st.append((h-1, w-1, 1))
    dp[h-1][w-1] = 0
else:
    st.append((h-1, w-1, 0))
    dp[h-1][w-1] = 1
delta = [(-1, 0), (0, -1)]
while st:
    x, y, c = st.popleft()
    for dx, dy in delta:
        if dx + x < 0 or y + dy < 0:
            continue
        if dp[dx + x][dy + y] != -1:
            continue
        dst_color = field[dx + x][dy + y] == "."
        if dst_color == c:
            dp[x + dx][y + dy] = dp[x][y]
            st.appendleft((dx + x, dy + y, dst_color))
        else:
            if dst_color == 0:
                dp[x + dx][y + dy] = dp[x][y] + 1
            else:
                dp[x + dx][y + dy] = dp[x][y]
            st.append((dx + x, dy + y, dst_color))


print(dp[0][0])

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
INF = 10**5
MOD = 10**9 + 7
sys.setrecursionlimit(100000000)

def main():
    h,w = map(int,input().split())
    grid = [list(input()) for _ in range(h)]

    dp = [[INF] * (w + 1) for _ in range(h + 1)]

    if grid[0][0] == '.':
        dp[1][1] = 0
    else:
        dp[1][1] = 1

    for i in range(h):
        for j in range(w):
            if i == 0 and j == 0:
                continue
            if grid[i][j] == '.':
                dp[i + 1][j + 1] = min(dp[i + 1][j],dp[i][j + 1])
            else:
                if j - 1 >= 0: 
                    if grid[i][j - 1] == '.':
                        dp[i + 1][j + 1] = min(dp[i + 1][j + 1],dp[i + 1][j] + 1)
                    else:
                        dp[i + 1][j + 1] = min(dp[i + 1][j + 1],dp[i + 1][j])
                if i - 1 >= 0:
                    if grid[i - 1][j] == '.':
                        dp[i + 1][j + 1] = min(dp[i + 1][j + 1],dp[i][j + 1] + 1)
                    else:
                        dp[i + 1][j + 1] = min(dp[i + 1][j + 1],dp[i][j + 1])
    
    print(dp[-1][-1])    
if __name__=='__main__':
    main()

Submission status: Accepted

Solution code:
h,w=map(int,input().split())
x=[[0]*w for _ in range(h)]
s=[input() for _ in range(h)]

if s[0][0]=="#": x[0][0]=1

for j in range(1,w):
    x[0][j]=x[0][j-1]
    if s[0][j]=="#" and s[0][j-1]==".": x[0][j]+=1

for i in range(1,h):
    x[i][0]=x[i-1][0]
    if s[i][0]=="#" and s[i-1][0]==".": x[i][0]+=1

for i in range(1,h):
    for j in range(1,w):
        if s[i][j]==".": x[i][j]=min(x[i][j-1],x[i-1][j])
        else:
            p=x[i][j-1];q=x[i-1][j]
            if s[i][j-1]==".": p+=1
            if s[i-1][j]==".": q+=1
            x[i][j]=min(p,q)


print(x[h-1][w-1])

Submission status: Accepted

Solution code:
h,w = map(int,input().split())
a = [list(input()) for i in range(h)]
dp = [[(1000,0) for i in range(w)] for j in range(h)]
if a[0][0] == ".":
  dp[0][0] = 0
  flg = 0
else:
  dp[0][0] = 1
  flg = 1
for i in range(h):
  for j in range(w):
    if i == j == 0:
      continue
    if i>0 and j == 0:
      dp[i][j] = dp[i-1][j]
      if a[i][j] != a[i-1][j]:
        dp[i][j] += 1
    elif j>0 and i == 0:
      dp[i][j] = dp[i][j-1]
      if a[i][j] != a[i][j-1]:
        dp[i][j] += 1
    else:
      if a[i][j] == a[i-1][j] and a[i][j] != a[i][j-1]:
        dp[i][j] = min(dp[i-1][j],dp[i][j-1]+1)
      if a[i][j] != a[i-1][j] and a[i][j] != a[i][j-1]:
        dp[i][j] = min(dp[i-1][j]+1,dp[i][j-1]+1)
      if a[i][j] == a[i-1][j] and a[i][j] == a[i][j-1]:
        dp[i][j] = min(dp[i-1][j],dp[i][j-1])
      if a[i][j] != a[i-1][j] and a[i][j] == a[i][j-1]:
        dp[i][j] = min(dp[i-1][j]+1,dp[i][j-1])
print((dp[-1][-1]+1)//2)

Submission status: Accepted

Solution code:
#from functools import lru_cache
#memo = lru_cache(None)
#from sys import setrecursionlimit as srl
#srl(2 * 10**5)
import heapq

rr = raw_input
rri = lambda: int(rr())
rrm = lambda: map(int, rr().split())

def solve(R, C, A):
    pq = [(0, 0, 0)]
    dist = {(0,0): 0}
    INF = float('inf')

    def neighbors(r, c):
        for nr, nc in ((r+1, c), (r, c+1)):
            if 0 <= nr < R and 0 <= nc < C:
                if A[nr][nc] == A[r][c]:
                    yield nr, nc, 0
                else:
                    yield nr, nc, 1
    while pq:
        d, r, c = heapq.heappop(pq)
        if d > dist.get((r, c), INF):
            continue
        if r==R-1 and c==C-1:
            if A[0][0]:
                return (d + 1) // 2
            else:
                return d // 2 + 1
            
        for nr, nc, w in neighbors(r, c):
            nd = d + w
            nei = nr, nc
            if nd < dist.get(nei, INF):
                heapq.heappush(pq, (nd, nr, nc))
                dist[nei] = nd
    return 0
        


for _ in xrange(1):
    R, C = rrm()
    A = []
    for _ in xrange(R):
        row = [c=='.' for c in rr()]
        A.append(row)

print solve(R, C, A)

Submission status: Accepted

Solution code:
H, W = map(int, input().split())

s = [list(input()) for _ in range(H)]

memo = [[None] * W for _ in range(H)]
memo[0][0] = (1 if s[0][0] == '#' else 0)

def dp(y, x):
    if memo[y][x] != None: return memo[y][x]
    #
    rets = []
    if y > 0:
        if s[y - 1][x] == '.' and s[y][x] == '#':
            rets.append(dp(y - 1, x) + 1)
        else:
            rets.append(dp(y - 1, x))
    if x > 0:
        if s[y][x - 1] == '.' and s[y][x] == '#':
            rets.append(dp(y, x - 1) + 1)
        else:
            rets.append(dp(y, x - 1))
    #
    ret = min(rets)
    memo[y][x] = ret
    return ret

print(dp(H - 1, W - 1))