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):
import sys, re, os
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians
from itertools import permutations, combinations, product, accumulate
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from fractions import gcd
 
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def S_MAP(): return map(str, input().split())
def LIST(): return list(map(int, input().split()))
def S_LIST(): return list(map(str, input().split()))
 
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7

H, W = MAP()
S = [input() for i in range(H)]

dp = [[INF] * W for i in range(H)]
dp[0][0] = 0







for h in range(1, H):
    if S[h][0] == S[h-1][0]:
        dp[h][0] = dp[h-1][0]
    else:
        dp[h][0] = dp[h-1][0] + 1


for w in range(1, W):
    if S[0][w] == S[0][w-1]:
        dp[0][w] = dp[0][w-1]
    else:
        dp[0][w] = dp[0][w-1] + 1


for i in range(1, H):
    for j in range(1, W):
        
        if S[i][j] == S[i-1][j] and S[i][j] == S[i][j-1]:
            dp[i][j] = min(dp[i-1][j], dp[i][j-1])
        elif S[i][j] != S[i-1][j] and S[i][j] == S[i][j-1]:
            dp[i][j] = min(dp[i-1][j]+1, dp[i][j-1])
        elif S[i][j] == S[i-1][j] and S[i][j] != S[i][j-1]:
            dp[i][j] = min(dp[i-1][j], dp[i][j-1]+1)            
        else:   
            dp[i][j] = min(dp[i-1][j]+1, dp[i][j-1]+1)


last = dp[H-1][W-1]
if S[0][0] == S[H-1][W-1] == ".":
    
    ans = last // 2
elif S[0][0] == S[H-1][W-1] == "
    ans = 1 + last // 2

elif S[0][0] != S[H-1][W-1]:
    ans = (last + 1) // 2
print(ans)



        
        
        
        




exit()


for i in range(1, H):
    for j in range(1, W):
        
        if S[i][j] == ".":
            dp[i][j] = min(dp[i-1][j], dp[i][j-1])
        else:
            dp[i][j] = min(dp[i-1][j], dp[i][j-1]) + 1

ans1 = dp[H-1][W-1]
print(dp)




S_r = []
for i in range(H):
    l = []
    for j in range(W):
        if S[i][j] == ".":
            l.append("
        else:
            l.append(".")
    S_r.append(l)
dp = [[INF] * W for i in range(H)]
S = deepcopy(S_r)
if S[0][0] == ".":
    dp[0][0] = 0
else:
    dp[0][0] = 1


for h in range(1, H):
    if S[h][0] == "
        dp[h][0] = dp[h-1][0] + 1
    else:
        dp[h][0] = dp[h-1][0]

for w in range(1, W):
    if S[0][w] == "
        dp[0][w] = dp[0][w-1] + 1
    else:
        dp[0][w] = dp[0][w-1]

for i in range(1, H):
    for j in range(1, W):
        
        if S[i][j] == ".":
            dp[i][j] = min(dp[i-1][j], dp[i][j-1])
        else:
            dp[i][j] = min(dp[i-1][j], dp[i][j-1]) + 1

ans2 = dp[H-1][W-1]

print(min(ans1, ans2+1))


exit()



























dp = [[0] * W for i in range(H)]


if S[0][0] == "
    dp[0][0] = 0
else:
    dp[0][0] = 1


for h in range(1, H):
    if S[h][0] == ".":
        dp[h][0] += dp[h-1][0] + 1
    else:
        dp[h][0] = dp[h-1][0]

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


for i in range(1, H):
    for j in range(1, W):
        
        if S[i][j] == "
            dp[i][j] = min(dp[i-1][j], dp[i][j-1])
        else:
            dp[i][j] = min(dp[i-1][j], dp[i][j-1]) + 1

ans2 = dp[H-1][W-1]

print(ans1, ans2)
print(min(ans1, ans2+1))

Solution (Python):
if __name__ == "__main__":
    H, W = list(map(int, input().split()))
    A = []
    for _ in range(H):
        s = input()
        A.append(s)

    cost = [[float("inf") for i in range(W)] for i in range(H)]

    cost[0][0] = 1 if A[0][0] == '

    for i in range(H)[1:]:
        if A[i-1][0] == '.' and A[i][0] == '
            cost[i][0] = cost[i-1][0] + 1
        else:
            cost[i][0] = cost[i-1][0]

    for j in range(W)[1:]:
        if A[0][j-1] == '.' and A[0][j] == '
            cost[0][j] = cost[0][j-1] + 1
        else:
            cost[0][j] = cost[0][j-1]

    for i in range(H)[1:]:
        for j in range(W)[1:]:

            
            if A[i][j-1] == '.' and A[i][j] == '
                cost_right = cost[i][j-1] + 1
            else:
                cost_right = cost[i][j-1]

            
            if A[i-1][j] == '.' and A[i][j] == '
                cost_down = cost[i-1][j] + 1
            else:
                cost_down = cost[i-1][j]

            cost[i][j] = min(cost_down, cost_right)

    
    print(cost[H-1][W-1])

Solution (Python):
import heapq

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

mat=[]
for i in range(H):
  array=[x=='.' for x in input()]
  mat.append(array)




graph={}
if mat[0][0]:
  graph[(0,0)]=[(1,1,0)]
else:
  graph[(0,0)]=[(1,1,1)]
  
for i in range(H):
  for j in range(W):
    graph[(i+1,j+1)]=[]
    if mat[i][j]:
      if i<H-1:
        if mat[i+1][j]:
          graph[(i+1,j+1)].append((i+2,j+1,0))
        else:
          graph[(i+1,j+1)].append((i+2,j+1,1))
      if j<W-1:
        if mat[i][j+1]:
          graph[(i+1,j+1)].append((i+1,j+2,0))
        else:
          graph[(i+1,j+1)].append((i+1,j+2,1))
    else:
      if i<H-1:
        graph[(i+1,j+1)].append((i+2,j+1,0))
      if j<W-1:
        graph[(i+1,j+1)].append((i+1,j+2,0))



dist={}
hq=[]
dist[(0,0)]=0
heapq.heappush(hq,(0,0,0))
for i in range(1,H+1):
  for j in range(1,W+1):
    dist[(i,j)]=10**9
    heapq.heappush(hq,(i+j,i,j))



while(True):
  if len(hq)==0:
    break

  ij,ii,jj=heapq.heappop(hq)
  
  candlist=graph[(ii,jj)]
  for cand in candlist:
    xx,yy,dd=cand
    dist[(xx,yy)]=min(dist[(xx,yy)],dist[(ii,jj)]+dd)
  
print(dist[(H,W)])

Solution (Python):



def main():
    h, w = map(int, input().split(" "))
    m = []
    for i in range(h):
        line = ['']
        line.extend(input())
        line[0] = line[1]
        m.append(line)
        if i == 0:
            m.append(line)
    dp = [[float("inf")] * (w + 1) for _ in range(h + 1)]
    if m[0][0] == "
        dp[0][1] = 1
        dp[1][0] = 1
    else:
        dp[0][1] = 0
        dp[1][0] = 0
    for i in range(1, h + 1):
        for j in range(1, w + 1):
            c = m[i][j]
            sh, sw = i - 1, j
            if dp[sh][sw] == dp[i][j -1]:
                if m[sh][sw] != c:
                    sh, sw = i, j - 1
            elif dp[sh][sw] > dp[i][j - 1]:
                sh, sw = i, j -1
            dp[i][j] = dp[sh][sw]
            if m[sh][sw] != c and c != '.':
                dp[i][j] += 1
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
    print(dp[h][w])


if __name__ == '__main__':
    main()

Solution (Python):
X = 10**4
H, W = map(int, input().split())


map_data = [['.' for j in range(W+1)] for i in range(H+1)]
for i in range(H):
    dat = list(input())
    for j in range(W):
        map_data[i+1][j+1] = dat[j]


r_map_data = [[X for j in range(W+1)] for i in range(H+1)]

r_map_data[0][1] = 0
r_map_data[1][0] = 0


for i in range(H):
    for j in range(W):
        
        t_val = r_map_data[i][j+1]
        
        if(map_data[i][j+1] == '.' and map_data[i+1][j+1] == '
            t_val += 1

        
        l_val = r_map_data[i+1][j]
        if(map_data[i+1][j] == '.' and map_data[i+1][j+1] == '
            l_val += 1

        val = min([t_val, l_val])
        
        r_map_data[i+1][j+1] = val

print(r_map_data[H][W])

Solution (Python):
import math
import fractions

def make_divisors(n):
    divisors = []
    for i in range(1, int(n**0.5)+1):
        if n % i == 0:
            divisors.append(i)
            if i != n // i:
                divisors.append(n//i)

    
    return divisors

def ValueToBits(x,digit):
    res = [0 for i in range(digit)]
    now = x
    for i in range(digit):
        res[i]=now%2
        now = now >> 1
    return res

def BitsToValue(arr):
    n = len(arr)
    ans = 0
    for i in range(n):
        ans+= arr[i] * 2**i
    return ans

def ValueToArray10(x, digit):
    ans = [0 for i in range(digit)]
    now = x
    for i in range(digit):
        ans[digit-i-1] = now%10
        now = now //10
    return ans
'''
def cmb(n, r, p):
    if (r < 0) or (n < r):
        return 0
    r = min(r, n - r)
    return fact[n] * factinv[r] * factinv[n-r] % p

p = 10 ** 9 + 7
N = 10 ** 6 + 2
fact = [1, 1]  
factinv = [1, 1]  
inv = [0, 1]  

for i in range(2, N + 1):
    fact.append((fact[-1] * i) % p)
    inv.append((-inv[p % i] * (p // i)) % p)
    factinv.append((factinv[-1] * inv[-1]) % p)
'''




h,w = list(map(int, input().split()))

s = []
for i in range(h):
    ss=[]
    a=input()
    for j in range(w):
        if(a[j]=='.'):
            ss.append(0)
        else:
            ss.append(1)
    s.append(ss)
        
dp = [[999 for j in range(w)]for i in range(h)]
dp[0][0] = s[0][0]

for i in range(h+w-2):
    for j in range(i+2):
        x = j
        y = i+1-j
        
        if(0<= x and x<=h-1 and 0<=y and y<=w-1):
            
            if(s[x][y]==0):
                dp[x][y] = min(dp[max(0,x-1)][y], dp[x][max(0,y-1)])
            else:
                if(x!=0 and s[x-1][y]==1):
                    dp[x][y] = dp[x-1][y]
                elif(x!=0 and s[x-1][y]==0):
                    dp[x][y] = dp[x-1][y]+1
                if(y!=0 and s[x][y-1]==1):
                    dp[x][y] = min(dp[x][y],dp[x][y-1])
                elif(y!=0 and s[x][y-1]==0):
                    dp[x][y] = min(dp[x][y],dp[x][y-1]+1)
                   




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

Solution (Python):
import itertools

H,W=map(int, input().split())
garden=[]

for i in range(H):
    garden.append(list(input().replace(".","1").replace("


dct=[(1,0),(0,1),(-1,0),(0,-1)]


start=(0,0)
goal=(H-1,W-1)
path=[start]
d=[ [i+j for i in range(W)] for j in range(H)]

done=[(0,0)]
for i, j in itertools.product(range(H),range(W)):
    color=garden[i][j]
    for each in dct:
        di,dj=each[0],each[1]
        if i+di<H and j+dj< W and i+di>=0 and j+dj>=0 and  garden[i+di][j+dj]==color:
            d[i+di][j+dj]=min(d[i+di][j+dj],d[i][j])
            done.append((i+di,j+dj))
            
            
        elif i+di<H and j+dj< W and i+di>=0 and j+dj>=0 :
            d[i+di][j+dj]=min(d[i+di][j+dj],d[i][j]+1)
            done.append((i+di,j+dj))
            
            
    
if int(garden[0][0])+int(garden[H-1][W-1])==0:
  print(int((d[H-1][W-1]+1)/2)+1)
else:
  print(int((d[H-1][W-1]+1)/2))

Solution (Python):


import sys

def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]
def ceil(x, y=1): return int(-(-x // y))
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(N=None): return list(MAP()) if N is None else [INT() for i in range(N)]
def Yes(): print('Yes')
def No(): print('No')
def YES(): print('YES')
def NO(): print('NO')
sys.setrecursionlimit(10 ** 9)
INF = 10 ** 18
MOD = 10 ** 9 + 7

def build_grid(H, W, intv, _type, space=True, padding=False):
    
    if space:
        _input = lambda: input().split()
    else:
        _input = lambda: input()
    _list = lambda: list(map(_type, _input()))
    
    if padding:
        offset = 1
    else:
        offset = 0
    grid = list2d(H+offset*2, W+offset*2, intv)
    for i in range(offset, H+offset):
        row = _list()
        for j in range(offset, W+offset):
            grid[i][j] = row[j-offset]
    return grid

H, W = MAP()
grid = build_grid(H, W, '*', str, space=0, padding=1)

dp = list2d(H+2, W+2, INF)
if grid[1][1] == '.':
    dp[1][1] = 0
else:
    dp[1][1] = 1
for i in range(H+1):
    for j in range(W+1):
        if grid[i][j] == grid[i][j+1]:
            dp[i][j+1] = min(dp[i][j+1], dp[i][j])
        else:
            dp[i][j+1] = min(dp[i][j+1], dp[i][j] + 1)  
        if grid[i][j] == grid[i+1][j]:  
            dp[i+1][j] = min(dp[i+1][j], dp[i][j])
        else:
            dp[i+1][j] = min(dp[i+1][j], dp[i][j] + 1)
ans = ceil(dp[H][W], 2)
print(ans)

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

a=[[0]*W for i in range(H)]
b=[[0]*W for i in range(H)]



for i in range(H):
	a[i]=list(input())

    
for j in range(1,W):
	b[0][j]=b[0][j-1]+int(not(a[0][j]==a[0][j-1]))

for i in range(1,H):
	b[i][0]=b[i-1][0]+int(not(a[i-1][0]==a[i][0]))
	for j in range(1,W):
		b[i][j]=min(b[i-1][j]+int(not(a[i-1][j]==a[i][j])),b[i][j-1]+int(not(a[i][j-1]==a[i][j])))

if(a[0][0]=="." and a[H-1][W-1]=="."):
	print(int(b[H-1][W-1]/2))
elif(a[0][0]=="
  print(int(b[H-1][W-1]/2+1))
else:
  print(int((b[H-1][W-1]+1)/2))

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

S = [""] * H

for i in range(H):
    S[i] = input()

dist = [[1000000 for i in range(W)] for j in range(H)]

dist[0][0] = 0 if S[0][0] == "." else 1

for i in range(H):
    for j in range(W):
        if i > 0:
            if S[i][j] == "
                dist[i][j] = min(dist[i][j], dist[i - 1][j] +
                                 (1 if S[i - 1][j] == "." else 0))
            else:
                dist[i][j] = min(dist[i][j], dist[i - 1][j])
        if j > 0:
            if S[i][j] == "
                dist[i][j] = min(dist[i][j], dist[i][j - 1] +
                                 (1 if S[i][j - 1] == "." else 0))
            else:
                dist[i][j] = min(dist[i][j], dist[i][j - 1])

print(dist[H - 1][W - 1])

Solution (Python):
from collections import deque

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

d = deque([[0,0,s[0][0]]])
distance = [[float("inf")]*W for _ in range(H)]
if s[0][0] == ".":
    distance[0][0] = 0
else:
    distance[0][0] = 1

while d:
    y, x, c = d.popleft()
    for new_y, new_x in ([int(y)+1, int(x)], [int(y), int(x)+1]):
        if 0 <= new_y <= H-1 and 0 <= new_x <= W-1:
            if c == "." and s[new_y][new_x] == "
                new_cost = distance[y][x] + 1
            else:
                new_cost = distance[y][x]
            if new_cost < distance[new_y][new_x]:
                distance[new_y][new_x] = new_cost
                d.append([new_y, new_x, s[new_y][new_x]])

print(distance[H-1][W-1])

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

result = [[10**5 for i in range(w)] for j in range(h)]
result[0][0] = 0
for i in range(h):
    for j in range(w):
        if j > 0:
            result[i][j] = result[i][j-1]+(sw[i][j-1]!=sw[i][j])
        if i > 0:
            result[i][j] = min(result[i][j], result[i-1][j]+(sw[i-1][j]!=sw[i][j]))


if sw[0][0]=="
    print(1+result[h-1][w-1]//2)
else:
    print(result[h-1][w-1]//2+(sw[0][0]!=sw[h-1][w-1]))

Solution (Python):
h,w = map(int,input().split())
s = [list(input()) for _ in range(h)]
dp = [[0 for _ in range(w)] for i in range(h)]
if s[0][0] == "
  dp[0][0] = 1
for i in range(1,w):
  if s[0][i] == "
    dp[0][i] = dp[0][i-1]
  elif s[0][i] == "
    dp[0][i] = dp[0][i-1]+1
  else:
    dp[0][i] = dp[0][i-1]
for i in range(1,h):
  if s[i][0] == "
    dp[i][0] = dp[i-1][0]
  elif s[i][0] == "
    dp[i][0] = dp[i-1][0]+1
  else:
    dp[i][0] = dp[i-1][0]
for i in range(1,h):
  for j in range(1,w):
    if s[i][j] == "
      if s[i-1][j] == "." and s[i][j-1] == ".":
        dp[i][j] = min(dp[i-1][j]+1,dp[i][j-1]+1)
      elif s[i-1][j] == ".":
        dp[i][j] = min(dp[i-1][j]+1,dp[i][j-1])
      elif s[i][j-1] == ".":
        dp[i][j] = min(dp[i-1][j],dp[i][j-1]+1)
      else:
        dp[i][j] = min(dp[i-1][j],dp[i][j-1])
    else:      
      dp[i][j] = min(dp[i-1][j],dp[i][j-1])

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

Solution (Python):
H,W=map(int,input().split())
s=[input() for _  in range(H)]
G=[[0 for j in range (W)] for i in range(H)]

if s[0][0]==".":G[0][0]=0
else:G[0][0]=1

for i in range(1,H):
    if s[i][0]==".":
        if s[i-1][0]==".":G[i][0]=G[i-1][0]
        if s[i-1][0]=="
    if s[i][0]=="
        if s[i-1][0]==".":G[i][0]=G[i-1][0]+1
        if s[i-1][0]=="

for i in range(1,W):
    if s[0][i]==".":
        if s[0][i-1]==".":G[0][i]=G[0][i-1]
        if s[0][i-1]=="
    if s[0][i]=="
        if s[0][i-1]==".":G[0][i]=G[0][i-1]+1
        if s[0][i-1]=="

for i in range(1,H):
    for j in range(1,W):
        if s[i][j]==".":
            G[i][j]=min(G[i-1][j],G[i][j-1])
        if s[i][j]=="
            if s[i-1][j]=="
            if s[i-1][j]=="." and s[i][j-1]=="
            if s[i-1][j]=="
            if s[i-1][j]=="." and s[i][j-1]==".":G[i][j]=min(G[i-1][j]+1,G[i][j-1]+1)

print(G[H-1][W-1])

Solution (Python):
import sys
import numpy as np
from collections import deque
sys.setrecursionlimit(10 ** 6)
input = sys.stdin.readline
H, W = [int(x) for x in input().strip().split()]
G = np.zeros((H, W), dtype=int)
pre = np.ones(W, dtype=int) * -1
NH = H
for h in range(H):
    s = np.array([1 if s == '
    if np.all(s == pre):
        NH -= 1
    else:
        G[h, :] = s
        pre = s

H = NH
C = [[float('inf') for _ in range(W)] for _ in range(H)]
pre = ''
def dfs(r, c, cost):
    
    C[r][c] = cost
    ret = deque([])
    q = deque([(r, c)])
    while q:
        cr, cc = q.popleft()
        
        for i, j in [(0, 1), (1, 0)]:
            if not(0 <= cr + i < H and 0 <= cc + j < W):
                continue
            if C[cr+i][cc+j] != float('inf'):
                continue
            if G[r][c] == G[cr+i][cc+j]:
                C[cr+i][cc+j] = cost
                q.append((cr+i, cc+j))
                if cr+i == H-1 and cc+j == W-1:
                    return ret
            else:
                ret.append((cr+i, cc+j))
    
    return ret
q = deque([(0, 0)])
cost = 0
while True:
    
    nq = deque([])
    if G[q[0][0]][q[0][1]] == 1:
        cost += 1
    for r, c in q:
        
        if C[r][c] != float('inf'):
            continue
        nq.extend(dfs(r, c, cost))
    q = nq
    
    
    if C[H-1][W-1] != float('inf'):
        print(C[H-1][W-1])
        exit()

Solution (Python):
import sys

grid = []
H, W = map(int, input().split(' '))
for i in range(H):
    grid.append(input())

dp = [[0 for i in range(W)] for j in range(H)]
if grid[0][0] == '
    dp[0][0] = 1

for i in range(1, H):
    dp[i][0] = dp[i-1][0] + (grid[i][0] == '

for j in range(1, W):
    dp[0][j] = dp[0][j-1] + (grid[0][j] == '

for i in range(1, H):
    for j in range(1, W):
        choice_1 = dp[i-1][j] + (grid[i][j] == '
        choice_2 = dp[i][j-1] + (grid[i][j] == '
        dp[i][j] = min(choice_1, choice_2)

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

Solution (Python):
H, W = map(int, input().split())
def change(x):
    if x == '
        return 1
    else:
        return 0
field = list()
for i in range(H):
    field.append(list(map(change,[i for i in input()])))

vector = [[1, 0], [0, 1]]
check_list = [[0 for _ in range(W)] for i in range(H)]
check_list[0][0] = 1
count_list = [[[0, [0, 0]] for _ in range(W)] for i in range(H)]
count_list[0][0][0] = field[0][0]
zahyo_check = [[(0, 0)]]
for i in range(H+W-2):
    zahyo = zahyo_check[i]
    zahyo_kari = list()
    for (y, x) in zahyo:
        for (dy, dx) in vector:
            v = count_list[y][x][0]
            y_k = y + dy
            x_k = x + dx
            try:
                if field[y_k][x_k] == 1 and field[y][x] == 0:
                    v += 1
                        
                if check_list[y_k][x_k] == 0:
                    count_list[y_k][x_k][0] = v
                    count_list[y_k][x_k][1] = [y, x]
                    check_list[y_k][x_k] = 1
                    zahyo_kari.append((y_k, x_k))
                    
                else:
                    if v < count_list[y_k][x_k][0]:
                        count_list[y_k][x_k][0] = v
                        count_list[y_k][x_k][1] = [y, x]
                        
            except:
                pass
    zahyo_check.append(zahyo_kari)

print(count_list[H-1][W-1][0])

Solution (Python):
from collections import deque

h,w = map(int,input().split())
F = [input() for _ in range(h)]
direct = [[0,1],[1,0]]
que = deque()
que.append([0,0])
INF = 10**5
dp = [[INF]*w for _ in range(h)]


dp[0][0] = 0

while len(que)>0:  
  y,x = que.popleft()    
  for dy,dx in direct:    
    ny = y+dy
    nx = x+dx
    if (0 <= nx < w) and (0 <= ny < h):
      if F[ny][nx] == F[y][x]:         
        if dp[ny][nx] > dp[y][x]:
          dp[ny][nx] = dp[y][x]
          que.append([ny,nx])
      else:                
        if dp[ny][nx] > dp[y][x] + 1 :        
          dp[ny][nx] = dp[y][x] + 1          
          que.append([ny,nx])   


ans = dp[-1][-1]//2
if F[0][0] == '
  ans += 1

print(ans)

Solution (Python):
h, w = map(int, input().split())
dp = [[0]] * h
m = [''] * h
inf = h * w

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



    
if m[0][0] == '
  dp[0][0] = 1


for i in range(h):
  for j in range(w):
    if i == 0 and j == 0:
      continue
    
    current = m[i][j]
    ue = '' if i == 0 else m[i-1][j]
    ue_val = inf if i == 0 else dp[i-1][j]
    left = '' if j == 0 else m[i][j-1]
    left_val = inf if j == 0 else dp[i][j-1]
    
    if current == '
      ue_val += 1
    if current == '
      left_val += 1
    
    dp[i][j] = min(ue_val, left_val)
        
        


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

Solution (Python):
def inp(wide):
    a = input()
    ans = []
    for i in range(wide):
        if a[i] == '.':
            ans.append(['w',float('Inf')])
        else:
            ans.append(['b',float('Inf')])
    return ans
def chang(up,left,nex): 
    if nex[0] == 'w':
        return min(up[1],left[1])
    else:
        d = up[1]
        g = left[1]
        if up[0] == 'w':
            d = d+1
        if left[0] == 'w':
            g = g+1
        return min(d,g)
def main(board,high,wide,already):
    for i in range(wide):
        if 0 <= already-i and already -i < high:
            nex = board[already-i][i]
            if 0 <= already-i-1 and 0 <= i-1:
                board[already-i][i][1] = chang(board[already-i-1][i],board[already-i][i-1],nex)
            elif 0 <= already-i-1 and 0 > i-1:
                board[already-i][i][1] = chang(board[already-i-1][i],['w',float('inf')],nex)
            else:
                board[already-i][i][1] = chang(['w',float('inf')],board[already-i][i-1],nex)
    
    if already == high + wide -1:
        return board[high-1][wide-1][1]
    return main(board,high,wide,already+1)
    

a = input().split()
high = int(a[0])
wide = int(a[1])

board = []
for i in range(high):
    board.append([])
    board[i] = inp(wide)
if board[0][0][0] == 'w':
    board[0][0][1] = 0
else:
    board[0][0][1] = 1

if high < wide:
    bo = []
    for i in range(wide):
        bo.append([])
        for j in range(high):
            bo[i].append(board[j][i])   
else:
    bo = board
ans = main(bo,max(wide,high),min(wide,high),1)
print(ans)

Solution (Python):
from heapq import heappush,heappop,heapify
from collections import deque,defaultdict,Counter
from itertools import permutations,combinations,groupby
import sys,bisect,string,math,time,functools,random
def Golf():*a,=map(int,open(0))
def I():return int(input())
def S_():return input()
def IS():return input().split()
def LS():return [i for i in input().split()]
def LI():return [int(i) for i in input().split()]
def LI_():return [int(i)-1 for i in input().split()]
def NI(n):return [int(input()) for i in range(n)]
def NI_(n):return [int(input())-1 for i in range(n)]
def StoLI():return [ord(i)-97 for i in input()]
def ItoS(n):return chr(n+97)
def LtoS(ls):return ''.join([chr(i+97) for i in ls])
def GI(V,E,Directed=False,index=0):
    org_inp=[];g=[[] for i in range(n)]
    for i in range(E):
        inp=LI();org_inp.append(inp)
        if index==0:inp[0]-=1;inp[1]-=1
        if len(inp)==2:
            a,b=inp;g[a].append(b)
            if not Directed:g[b].append(a)
        elif len(inp)==3:
            a,b,c=inp;aa=(inp[0],inp[2]);bb=(inp[1],inp[2]);g[a].append(bb)
            if not Directed:g[b].append(aa)
    return g,org_inp
def GGI(h,w,search=None,replacement_of_found='.',mp_def={'

    mp=[1]*(w+2);found={}
    for i in range(h):
        s=input()
        for char in search:
            if char in s:
                found[char]=((i+1)*(w+2)+s.index(char)+1)
                mp_def[char]=mp_def[replacement_of_found]
        mp+=[1]+[mp_def[j] for j in s]+[1]
    mp+=[1]*(w+2)
    return h+2,w+2,mp,found
def TI(n):return GI(n,n-1)
def bit_combination(k,n=2):return [[tb//(n**bt)%n for bt in range(k)] for tb in range(n**k)]
def show(*inp,end='\n'):
    if show_flg:print(*inp,end=end)

YN=['YES','NO'];Yn=['Yes','No']
mo=10**9+7
inf=float('inf')
l_alp=string.ascii_lowercase

input=lambda: sys.stdin.readline().rstrip()

def ran_input():
    n=random.randint(4,16)
    rmin,rmax=1,10
    a=[random.randint(rmin,rmax) for _ in range(n)]
    return n,a

show_flg=False
show_flg=True

h,w=LI()
h,w,g,sg=GGI(h,w,search=['S','G'],replacement_of_found='.',mp_def={'
dp=[10**6]*(h*w)
g[1],dp[1]=0,0

for j in range(h*w-h):
    r,c=j//w,j%w
    if (r in [0,h-1]) or (c in [0,w-1]):
      	if j!=1:
            continue

    dp[j+1]=min(dp[j]+1 if (g[j],g[j+1])==(0,1) else dp[j],dp[j+1])
    dp[j+w]=min(dp[j]+1 if (g[j],g[j+w])==(0,1) else dp[j],dp[j+w])

print(dp[(h-2)*w+w-2])

Solution (Python):
def inputs(): return [int(x) for x in input().split()]
h,w = inputs()
meiro=[list(input()) for _ in range(h)]
visit = [[-1]*w for _ in range(h)]
if meiro[0][0]=="
    visit[0][0]=1
else:
    visit[0][0]=0
for j in range(1,w):
    if meiro[0][j]=="
        if meiro[0][j-1]=="
            visit[0][j]=visit[0][j-1]
        else:
            visit[0][j]=visit[0][j-1]+1
    if meiro[0][j]==".":
        visit[0][j]=visit[0][j-1]
for i in range(1,h):
    if meiro[i][0]=="
        if meiro[i-1][0]=="
            visit[i][0]=visit[i-1][0]
        else:
            visit[i][0]=visit[i-1][0]+1
    if meiro[i][0]==".":
        visit[i][0]=visit[i-1][0]

for i in range(1,h):
    for j in range(1,w):
        if meiro[i][j]=="
            if meiro[i-1][j]=="
                visit[i][j]=min(visit[i-1][j],visit[i][j-1])
            elif meiro[i-1][j]=="
                visit[i][j]=min(visit[i-1][j],visit[i][j-1]+1)
            elif meiro[i][j-1]=="
                visit[i][j]=min(visit[i-1][j]+1,visit[i][j-1])
            else:
                visit[i][j]=min(visit[i-1][j]+1,visit[i][j-1]+1)
        else:
            visit[i][j]=min(visit[i-1][j],visit[i][j-1])
print(visit[h-1][w-1])

Solution (Python):
d = input().split(" ")
h = int(d[0])
w = int(d[1])
l = []
for i in range(h):
	s = input()
	l.append(list(s))
f = 0
p = l[0][0]
a = [[201] * w for i in range(h)]
a[0][0] = 0
for i in range(1, h):
	if p == l[i][0]:
		a[i][0] = a[i-1][0]
	else:
		a[i][0] = a[i-1][0] + 1
	p = l[i][0]
p = l[0][0]
for i in range(1, w):
	if p == l[0][i]:
		a[0][i] = a[0][i-1]
	else:
		a[0][i] = a[0][i-1] + 1
	p = l[0][i]
for i in range(1, h):
	for j in range(1, w):
		x = a[i-1][j]
		y = a[i][j-1]
		if l[i-1][j] != l[i][j]:
			x += 1
		if l[i][j-1] != l[i][j]:
			y += 1
		a[i][j] = min(x, y)
if l[0][0] == "." and l[h-1][w-1] == ".":
	print(int(a[h-1][w-1]/2))
elif l[0][0] == "." and l[h-1][w-1] == "
	print(int((a[h-1][w-1]+1)/2))
elif l[0][0] == "
	print(int((a[h-1][w-1]+1)/2))
elif l[0][0] == "
	print(int((a[h-1][w-1]/2) + 1))

Solution (Python):
def main():
    import sys
    from collections import deque
    input = sys.stdin.readline

    H, W = map(int, input().split())
    grid = []
    for _ in range(H):
        grid.append(input().rstrip('\n'))

    d = [(1, 0), (0, 1)]
    que = deque()
    que.append((0, 0))
    seen = [[-1] * W for _ in range(H)]
    if grid[0][0] == '
        seen[0][0] = 1
    else:
        seen[0][0] = 0
    while que:
        h, w = que.popleft()
        for dh, dw in d:
            h_new, w_new = h+dh, w+dw
            if 0 <= h_new < H and 0 <= w_new < W:
                if seen[h_new][w_new] == -1:
                    if grid[h_new][w_new] == grid[h][w]:
                        seen[h_new][w_new] = seen[h][w]
                        que.appendleft((h_new, w_new))
                    else:
                        if grid[h_new][w_new] == '
                            seen[h_new][w_new] = seen[h][w] + 1
                        else:
                            seen[h_new][w_new] = seen[h][w]
                        que.append((h_new, w_new))
    print(seen[-1][-1])
    


if __name__ == '__main__':
    main()

Solution (Python):
from collections import deque
from heapq import heappush, heappop
h, w = map(int, input().split())
grid = [input() for _ in range(h)]

def solve(grid, h, w):
    if h == 0 or w == 0:
        return 0
    color = grid[0][0]
    cnt = 0
    if color == '
        cnt += 1
    dist = [[-1] * w for _ in range(h)]
    dist[0][0] = cnt
    q = []
    q.append((0, 0))
    current_color_cluster = [(0, 0)]
    while q and dist[h - 1][w - 1] == -1:
        new_q = []
        for i, j in q:
            for ii, jj in ((i + 1, j), (i, j + 1)):
                if 0 <= ii < h and 0 <= jj < w and dist[ii][jj] == -1 and grid[ii][jj] == color:
                    dist[ii][jj] = cnt
                    new_q.append((ii, jj))
        if new_q:
            current_color_cluster.extend(new_q)
            q = new_q
        elif dist[h - 1][w - 1] == -1:
            if color == '.':
                cnt += 1
            color = '
            q = current_color_cluster
            current_color_cluster = []
    return dist[h - 1][w - 1]

print(solve(grid, h, w))

Solution (Python):
H, W = map(int, input().split())
s = []
for _ in range(H):
    s += [list(input())]

ls = [[0]*W for _ in range(H)]
ls[0][0] = int(bool(s[0][0]=="

for i in range(1,W):
    ls[0][i] = ls[0][i-1]+ int(bool(s[0][i]=="
    
for j in range(1,H):
    ls[j][0] = ls[j-1][0]+ int(bool(s[j][0]=="

for i in range(1,W):
    for j in range(1,H):
        ls[j][i] = min(ls[j][i-1]+ int(bool(s[j][i]=="
                       ls[j-1][i]+ int(bool(s[j][i]=="
        
print(ls[-1][-1])