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

Solution (Python):
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] == "
    while stack:
        h, w = stack.popleft()



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

Solution (Python):
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] == '
        d = 100000000 if i == 0 else dp[a][j]+1 if ss[i][j] == '
        dp[i][j] = min(c,d)

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

Solution (Python):
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] == '
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])

Solution (Python):
















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

Solution (Python):
H,W = map(int,input().split())
S = [[c=="

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

Solution (Python):
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))

Solution (Python):
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))

Solution (Python):
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] != '
            up = dp[c-1][r]+1 if grid[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])

Solution (Python):
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)

Solution (Python):
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)

Solution (Python):
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())

s = []
for _ in range(H):
    s.append(input())



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

row = []
col = []
dist = []
for h in range(H):
    for w in range(W):








        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] == '
    print(d // 2 + 1)
else:
    print(d // 2 + 1)

Solution (Python):
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] == "
                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[H-1][W-1])

 

if __name__ == '__main__':
    main()

Solution (Python):

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

Solution (Python):
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()

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

if s[0][0]=="

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

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

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

Solution (Python):
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)

Solution (Python):




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)

Solution (Python):
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] == '

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

Solution (Python):

h,w = list(map(int,input().split()))
board = []
for _ in range(h):
    board.append(list(input()))
inf=float("inf")
dp = [[inf] * w for _ in range(h)]

if board[0][0]==".":
    dp[0][0]=0
else:
    dp[0][0]=1

for i in range(1,w):
    pre = board[0][i-1]
    if board[0][i]==".":
        dp[0][i]=dp[0][i-1]
    else:
        if pre==board[0][i]:
            dp[0][i]=dp[0][i-1]
        else:
            dp[0][i]=dp[0][i-1]+1

for i in range(1,h):
    for j in range(w):
        if j==0:
            if board[i][j]=="
                dp[i][j]=dp[i-1][j]+1
            else:
                dp[i][j]=dp[i-1][j]
        else:
            if board[i][j]=="
                left_add = 0
                up_add = 0
                if board[i][j-1]==".":
                    left_add=1
                if board[i-1][j]==".":
                    up_add=1
                dp[i][j]=min(dp[i-1][j]+up_add,dp[i][j-1]+left_add)
            else:
                dp[i][j]=min(dp[i-1][j],dp[i][j-1])
print(dp[-1][-1])

Solution (Python):
import sys
from collections import deque
readline = sys.stdin.readline
H, W = map(int, readline().split())
G = [list(map(lambda x: 1 if x == '.' else 0, readline().strip())) for _ in range(H)]

dist = [[0]*W for _ in range(H)]

Q = deque([(0, 0)])
used = set(Q)
dim = [(0, 1), (1, 0)]
while Q:
    nx, ny = Q.pop()
    for dx, dy in dim:
        fx, fy = nx+dx, ny+dy
        if not 0 <= fx < H or not 0 <= fy < W:
            continue
        if (fx, fy) in used:
            continue
        used.add((fx, fy))
        if G[nx][ny] == G[fx][fy]:
            dist[fx][fy] = dist[nx][ny]
            Q.append((fx, fy))
        else:
            dist[fx][fy] = 1 + dist[nx][ny]
            Q.appendleft((fx, fy))

K = dist[H-1][W-1]
if G[0][0] == 0:
    K += 1
if G[H-1][W-1] == 0:
    K += 1
print(K//2)

Solution (Python):
h, w = map(int, input().split())
cells = []
for hh in range(h):
    row = list(input())
    cells.append(row)


dp = [[0 for c in range(w)] for r in range(h)]

if cells[0][0] == '
    dp[0][0] = 1
else:
    dp[0][0] = 0

r = 0
for c in range(1,w):
    if cells[r][c] != cells[r][c-1] and cells[r][c] == "
        dp[r][c] = dp[r][c-1] + 1
    else:
        dp[r][c] = dp[r][c-1]
c = 0        
for r in range(1,h):
    if cells[r][c] != cells[r-1][c] and cells[r][c] == "
        dp[r][c] = dp[r-1][c] + 1
    else:
        dp[r][c] = dp[r-1][c]

for r in range(1,h):
    for c in range(1,w):
        upper = dp[r-1][c]
        if cells[r][c] != cells[r-1][c] and cells[r][c] == '
            upper += 1
        left = dp[r][c-1]
        if cells[r][c] != cells[r][c-1] and cells[r][c] == '
            left += 1
        dp[r][c] = min(left, upper)
print(dp[-1][-1])

Solution (Python):
def examA():
    def bfs_grid(h, w, s, maze):
        distance = [[inf] * w for _ in range(h)]

        def bfsg():
            queue = deque()
            if maze[s[0]][s[1]]=="
                queue.append((s, 1))
                distance[s[0]][s[1]] = 1
            else:
                queue.append((s,0))
                distance[s[0]][s[1]] = 0
            while len(queue):
                [y, x],st = queue.popleft()
                for i in range(2):
                    nx, ny = x + [1, 0][i], y + [0, 1][i]
                    if (0 <= nx < w and 0 <= ny < h):
                        cur = deepcopy(distance[y][x])
                        if st==0 and maze[ny][nx]=='
                            cur += 1
                        if distance[ny][nx] <= cur:
                            continue
                        if maze[ny][nx]=='
                            queue.append(((ny, nx),1))
                        else:
                            queue.append(((ny, nx), 0))
                        distance[ny][nx] = cur
            return distance

        return bfsg()
    H, W = LI()
    S = [SI()for _ in range(H)]
    L = bfs_grid(H,W,[0,0],S)
    ans = L[-1][-1]
    
    print(ans)
    return

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

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

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

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

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

import sys,bisect,itertools,heapq,math,random
from copy import deepcopy
from heapq import heappop,heappush,heapify
from collections import Counter,defaultdict,deque
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))
def LSI(): return list(map(str,sys.stdin.readline().split()))
def LS(): return sys.stdin.readline().split()
def SI(): return sys.stdin.readline().strip()
global mod,mod2,inf,alphabet,_ep
mod = 10**9 + 7
mod2 = 998244353
inf = 10**18
_ep = 10**(-12)
alphabet = [chr(ord('a') + i) for i in range(26)]

sys.setrecursionlimit(10**6)

if __name__ == '__main__':
    examA()

"""

"""

Solution (Python):
import sys
import itertools
input = sys.stdin.readline
sys.setrecursionlimit(100000)
mod = 10 ** 9 + 7

def read_values(): return map(int, input().split())
def read_index(): return map(lambda x: int(x) - 1, input().split())
def read_list(): return list(read_values())
def read_lists(N): return [read_list() for n in range(N)]


class v:
    def __init__(self, f):
        self.f = f
        self.v = None
 
    def __str__(self):
        return str(self.v)
 
    def ud(self, n):
        if self.v is None:
            self.v = n
        else:
            self.v = self.f(self.v, n) 


def main():
    H, W = read_values()
    F = ["." * (W + 2)] + ["." + input() + "." for _ in range(H)] + ["." * (W + 2)]
    dp = [[10 ** 10 for _ in range(W + 2)] for __ in range(H + 2)]
    dp[1][0] = 0
    dp[0][1] = 0
    for h in range(1, H + 1):
        for w in range(1, W + 1):
            if F[h][w] == ".":
                dp[h][w] = min(dp[h - 1][w], dp[h][w - 1])
            else:
                hr = 0 if F[h - 1][w] == "
                wr = 0 if F[h][w - 1] == "
                dp[h][w] = min(dp[h - 1][w] + hr, dp[h][w - 1] + wr)
    print(dp[H][W])


if __name__ == "__main__":
    main()

Solution (Python):
H,W = list(map(int,input().split()))
MAP = [input() for i in range(H)]
  
DP = [[0 for w in range(W)]for h in range(H)]

for w in range(W):
  for h in range(H):
    if h + w == 0:
      if MAP[0][0] == "
        DP[0][0] = 1
      continue
    elif h == 0:
      if MAP[h][w-1]+MAP[h][w]==".
        DP[h][w] = DP[h][w-1] +1
      else:
        DP[h][w] = DP[h][w-1]
    elif w == 0:
      if MAP[h-1][w]+MAP[h][w] ==".
        DP[h][w] = DP[h-1][w]+1
      else:
        DP[h][w] = DP[h-1][w]
    else:
      DP[h][w] = min(
        DP[h-1][w] + (1 if MAP[h-1][w]+MAP[h][w] == ".
        DP[h][w-1] + (1 if MAP[h][w-1]+MAP[h][w] == ".
      )

print(DP[-1][-1])

Solution (Python):

h,w = map(int,input().split())
sl = []
for _ in range(h):
    s = list(input())
    sl.append(s)

dp = [[float("inf") for i in range(w)] for j in range(h)]
if sl[0][0] == ".":
    dp[0][0] = 0
else:
    dp[0][0] = 1

for i in range(h):
    for j in range(w):
        if j != w-1:
            if sl[i][j+1] != sl[i][j]:
                dp[i][j+1] = min(dp[i][j] + 1, dp[i][j+1])
            else:
                dp[i][j + 1] = min(dp[i][j], dp[i][j + 1])
        if i != h-1:
            if sl[i+1][j] != sl[i][j]:
                dp[i+1][j] = min(dp[i][j] + 1, dp[i+1][j])
            else:
                dp[i+1][j] = min(dp[i][j], dp[i+1][j])
def ceil(a, b):
   return a // b + (a % b > 0)

print(ceil(dp[-1][-1],2))

Solution (Python):
from collections import deque


def solve(h, w, field):
    s = int(field[0][0] == '
    q = deque([(s, s, 0, 0)])
    visited = [[[False] * 2 for _ in range(w)] for _ in range(h)]
    while q:
        cost, state, i, j = q.popleft()
        if visited[i][j][state]:
            continue
        visited[i][j][state] = True
        if i == h - 1 and j == w - 1:
            return cost

        for ni, nj in [(i, j + 1), (i + 1, j)]:
            if ni == h or nj == w:
                continue
            nc = int(field[ni][nj] == '
            if state == 0 and nc == 1:
                q.append((cost + 1, nc, ni, nj))
            else:
                q.appendleft((cost, nc, ni, nj))


h, w = list(map(int, input().split()))
field = [input() for _ in range(h)]
print(solve(h, w, field))

Solution (Python):

import numpy as np
from functools import *
import sys
sys.setrecursionlimit(100000)
input = sys.stdin.readline


def acinput():
    return list(map(int, input().split(" ")))




H,W=acinput()

field=[]
dp=np.zeros([H,W])

for i in range(H):
    field.append(list(input()))
    
dp[0,0]=(field[0][0]=="

def g(a,b):
    if a=="." and b=="
        return 1
    return 0

j=0    
for i in range(1,H):
    dp[i,j]=dp[i-1, j]+g(field[i-1][j],field[i][j])
    
i = 0
for j in range(1,W):
    dp[i, j] = dp[i, j-1]+g(field[i][j-1],field[i][j])


for i in range(1,H):
    for j in range(1,W):
        l=dp[i,j-1]+g(field[i][j-1],field[i][j])
        u = dp[i-1, j]+g(field[i-1][j], field[i][j])
        dp[i,j]=min(l,u)


print(int(dp[H-1,W-1]))

Solution (Python):
h,w=map(int,input().split())
l=[[i for i in input()] for j in range(h)]
INF=float('inf')
dp=[[INF for j in range(w)] for i in range(h)]
dp[0][0]=0
if l[0][0]=="
    dp[0][0]+=1
if l[-1][-1]=="
    dp[0][0]+=1
for i in range(1,w):
    if l[0][i-1]==l[0][i]:
        dp[0][i]=dp[0][i-1]
    else:
        dp[0][i]=dp[0][i-1]+1
for i in range(1,h):
    for j in range(w):
        if l[i-1][j]==l[i][j]:
            dp[i][j]=dp[i-1][j]
        else:
            dp[i][j]=dp[i-1][j]+1
        if j==0:
            continue
        if l[i][j-1]==l[i][j]:
            dp[i][j]=min(dp[i][j],dp[i][j-1])
        else:
            dp[i][j]=min(dp[i][j],dp[i][j-1]+1)
print(dp[-1][-1]//2)

Solution (Python):
h, w = map(int, input().split())

info = ["." + "x" * (w - 1)] + [input() for i in range(h)]
INF = 10 ** 5
h += 1
dp = [[INF] * w for i in range(h)]
dp[0][0] =  0

for i in range(h):
    for j in range(w):
        for ii, jj in [(i, j + 1), (i + 1, j)] :
            if not(0 <= ii < h and 0 <= jj < w):
                continue
            if info[ii][jj] == "x":
                continue
            if info[i][j] != info[ii][jj] and info[ii][jj] == "
                dp[ii][jj] = min(dp[i][j] + 1, dp[ii][jj])
            else:
                dp[ii][jj] = min(dp[i][j], dp[ii][jj])
print(dp[-1][-1])

Solution (Python):
from collections import deque
from functools import lru_cache

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

minDist = [[10**10] * W for _ in range(H)]
que = deque([(0, 0, 0 if S[0][0] == '.' else 1, S[0][0] == '.')])

while que:
    h, w, dist, isWhite = que.popleft()

    if minDist[h][w] <= dist:
        continue
    minDist[h][w] = dist

    if h + 1 < H:
        isNextWhite = S[h + 1][w] == '.'
        if isWhite and not isNextWhite:
            que.append((h + 1, w, dist + 1, isNextWhite))
        else:
            que.appendleft((h + 1, w, dist, isNextWhite))
    if w + 1 < W:
        isNextWhite = S[h][w + 1] == '.'
        if isWhite and not isNextWhite:
            que.append((h, w + 1, dist + 1, isNextWhite))
        else:
            que.appendleft((h, w + 1, dist, isNextWhite))

ans = minDist[H - 1][W - 1]
print(ans)

Solution (Python):
h,w=map(int,input().split())
s=[]
for i in range(h):
	ss=input()
	s.append(ss)
inf=10**4
dp=[[inf]*w for _ in range(h)]
if s[0][0]=="
	dp[0][0]=1
else:
	dp[0][0]=0
for i in range(w-1):
	if s[0][i+1]==".":
		dp[0][i+1]=dp[0][i]
	else:
		dp[0][i+1]=dp[0][i]+1
		if s[0][i]=="
			dp[0][i+1]-=1
for i in range(1,h):
	if s[i][0]==".":
		dp[i][0]=dp[i-1][0]
	else:
		dp[i][0]=dp[i-1][0]+1
		if s[i-1][0]=="
			dp[i][0]-=1
	for j in range(1,w):
		if s[i][j]==".":
			dp[i][j]=min(dp[i][j-1],dp[i-1][j])
		else:
			p=dp[i][j-1]
			q=dp[i-1][j]
			if s[i][j-1]=="
				p-=1
			if s[i-1][j]=="
				q-=1
			dp[i][j]=min(p,q)+1
print(dp[-1][-1])

Solution (Python):
import numpy as np
h, w = list(map(int, input().split()))
ss = []
for _ in range(h):
    s = input()
    s = s.replace(".", "0").replace("
    s = list(map(int, list(s)))
    ss.append(s)
ss = np.array(ss)
    

dp = np.zeros((h, w)).astype(np.int32)
if ss[0,0] == 1:
    dp[0,0] = 1
    

for kh in range(h):
    for kw in range(w):


        if kh == 0 and kw == 0:
            continue
        if kh == 0:
            a = 9999
        else:
            if ss[kh - 1, kw] == 0 and ss[kh, kw] == 1:
                a = dp[kh - 1, kw] + 1
            else:
                a = dp[kh - 1, kw]

        if kw == 0:
            b = 9999
        else:
            if ss[kh, kw - 1] == 0 and ss[kh, kw] == 1:
                b = dp[kh, kw - 1] + 1
            else:
                b = dp[kh, kw - 1]

        dp[kh, kw] = min([a, b])

print(dp[-1, -1])

Solution (Python):
h, w = map(int, input().split())
f = [input() for _ in range(h)]

inf = 10 ** 18
d = [[inf for _ in range(w)] for _ in range(h)]
d[0][0] = 0

for j in range(1, w):
    if f[0][j] == f[0][j-1]:
        d[0][j] =  d[0][j-1]
    else:
        d[0][j] =  d[0][j-1] + 1

for i in range(1, h):
    if f[i][0] == f[i-1][0]:
        d[i][0] =  d[i-1][0]
    else:
        d[i][0] =  d[i-1][0] + 1

for i in range(1, h):
    for j in range(1, w):
        costi = int(f[i][j] != f[i-1][j])
        costj = int(f[i][j] != f[i][j-1])
        d[i][j] = min(d[i-1][j] + costi, d[i][j-1] + costj)

if f[0][0] == '.':
    print((d[h-1][w-1]+1)//2)
else:
    print(d[h-1][w-1]//2 + 1)

Solution (Python):
h, w = map(int, input().split())
smap = []
for _ in range(h):
    di = list(input())
    smap.append(di)

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

for i in range(h):
    for j in range(w):
        if i == j == 0:
            continue
        if i == 0:
            if smap[i][j-1] != smap[i][j]:
                dp[i][j] = dp[i][j-1]+1
            else:
                dp[i][j] = dp[i][j-1]
        elif j == 0:
            if smap[i-1][j] != smap[i][j]:
                dp[i][j] = dp[i-1][j]+1
            else:
                dp[i][j] = dp[i-1][j]
        else:
            up = 0
            if smap[i][j-1] != smap[i][j]:
                up = dp[i][j-1]+1
            else:
                up = dp[i][j-1]
            lp = 0
            if smap[i-1][j] != smap[i][j]:
                lp = dp[i-1][j]+1
            else:
                lp = dp[i-1][j]
            dp[i][j] = min(up, lp)
result = dp[h-1][w-1] // 2
if dp[h-1][w-1] %2 == 1:
    result += 1
if smap[0][0] == '
    result+=1
print(result)