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
h,w=map(int,input().split())
field=[["*" for i in range(w+2)]]+[["*"]+list(input())+["*"] for i in range(h)]+[["*" for i in range(w+2)]]
cost=[[500 for i in range(w+2)] for j in range(h+2)]
cost[1][1]=0
ans=0
for i in range(1,h+1):
    for j in range(1,w+1):
        color=field[i][j]
        if color=="." and field[i][j+1]=="
            cost[i][j+1]=min(cost[i][j]+1,cost[i][j+1])
        else:cost[i][j+1]=min(cost[i][j],cost[i][j+1])
        if color=="." and field[i+1][j]=="
            cost[i+1][j]=min(cost[i][j]+1,cost[i+1][j])
        else:cost[i+1][j]=min(cost[i][j],cost[i+1][j])
print(cost[h][w] if field[1][1]=="." else cost[h][w]+1)

Solution (Python):
import bisect,collections,copy,itertools,math,string
def I(): return int(input())
def S(): return input()
def LI(): return list(map(int,input().split()))
def LS(): return list(input().split())

H,W = LI()
S = [S() for _ in range(H)]
dp = [[-1]*W for _ in range(H)]
for i in range(H):
    for j in range(W):
        judge = 1 if S[i][j]=='
        if i==0: 
            if j==0:
                dp[0][0] = judge
            else:
                dp[0][j] = dp[0][j-1]+judge*(0 if S[0][j-1]=='
        else: 
            if j==0:
                dp[i][0] = dp[i-1][0]+judge*(0 if S[i-1][j]=='
            else:
                temp1 = dp[i][j-1]+judge*(0 if S[i][j-1]=='
                temp2 = dp[i-1][j]+judge*(0 if S[i-1][j]=='
                dp[i][j] = min(temp1,temp2)
print(dp[-1][-1])

Solution (Python):









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

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

maze = []
for i in range(h):
    sub = list(input())
    maze.append(sub)

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

    else:
        dp[0][i] = dp[0][i - 1]
for j in range(1, h):
    if maze[j - 1][0] == "." and maze[j][0] == "
        dp[j][0] = dp[j - 1][0] + 1
    else:
        dp[j][0] = dp[j - 1][0]

for i in range(1, h):
    for j in range(1, w):
        d = dp[i - 1][j]
        e = dp[i][j - 1]
        if maze[i - 1][j] == "." and maze[i][j] == "
            d += 1
        if maze[i][j - 1] == "." and maze[i][j] == "
            e += 1
        dp[i][j] = min(d, e)
print(dp[h - 1][w - 1])

Solution (Python):
H,W = map(int,input().split())
S = [input() for i in range(H)]

dp = [[-1]*W for i in range(H)]
if S[0][0] == "
    dp[0][0] = 1
else:
    dp[0][0] = 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 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 h in range(1,H):
    for w in range(1,W):
        if S[h][w] == "
            dw = dp[h][w-1] + 1
        else:
            dw = dp[h][w-1]
            
        if S[h][w] == "
            dh = dp[h-1][w] + 1
        else:
            dh = dp[h-1][w]
            
        dp[h][w] = min(dw,dh)
        
print(dp[-1][-1])

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

dp = []
for i in range(h):
    dp.append([0 for j in range(w)])

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

for i in range(h):
    for j in range(w):
        if i == 0:
            if j != 0:
                dp[i][j] = dp[i][j-1] + need_or_not(s[i][j-1], s[i][j])
            else:
                if s[0][0] == "
                    dp[0][0] = 1
        else:
            if j!= 0:
                dp[i][j] = min(dp[i-1][j] + need_or_not(s[i-1][j], s[i][j]), dp[i][j-1] + need_or_not(s[i][j-1], s[i][j]))
            else:
                dp[i][j] = dp[i-1][j] + need_or_not(s[i-1][j], s[i][j])

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

Solution (Python):
h,w=map(int,input().split())
s=[[+(i=='
c=[1000]*w*h
c[0]=s[0][0]
for i in range(h):
  for j in range(w):
    for k,l in [[i-1,j],[i,j-1]]:
      if k<0 or l<0:continue
      c[i*w+j]=min(c[i*w+j],c[k*w+l]+(s[k][l]==0)*(s[i][j]==1))
print(c[-1])

Solution (Python):
H, W = map(int,input().split())
maze = [list(input()) for _ in range(H)]
dist = [[-1 for _ in range(W)] for _ in range(H)]

if maze[0][0] == '
    dist[0][0] = 1
else:
    dist[0][0] = 0

for w in range(1, W):
    if maze[0][w-1] == '.' and maze[0][w] == '
        dist[0][w] = dist[0][w-1] + 1
    else:
        dist[0][w] = dist[0][w-1]

for h in range(1, H):
    if maze[h-1][0] == '.' and maze[h][0] == '
        dist[h][0] = dist[h-1][0] + 1
    else:
        dist[h][0] = dist[h-1][0]

for h in range(1, H):
    for w in range(1, W):
        if maze[h][w-1] == '.' and maze[h][w] == '
            dw = dist[h][w-1] + 1
        else:
            dw = dist[h][w-1]
        if maze[h-1][w] == '.' and maze[h][w] == '
            dh = dist[h-1][w] + 1
        else:
            dh = dist[h-1][w]
        dist[h][w] = min(dw, dh)

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

Solution (Python):
from itertools import *
from heapq import *

def solve(H, W, grid):
  goal = (H-1, W-1)
  fixed = set()
  candicates = [(grid[0,0], (0, 0))]
  while 1:
    dist, p = heappop(candicates)
    if p == goal:
      return dist
    if p in fixed:
      continue
    fixed.add(p)
    for i in range(2):
      p1 = p[0]+i, p[1]+(1-i)
      if not (p1[0]<H and p1[1]<W) or p1 in fixed:
        continue
      x, y = p
      x1, y1 = p1
      heappush(candicates, (dist+(grid[p1] & ~grid[p]), p1))
  return None

H, W = map(int, input().split())
grid = {(i,j): int(c=="

print(solve(H, W, grid))

Solution (Python):


import sys

sys.setrecursionlimit(10 ** 6)

class Logger:
	def __init__(self, is_debug):
		self.debug = is_debug
	def print(self, *arg):
		if self.debug:
			print("logger:", *arg)
	def plane(self, lst, sep=" ", space=0):
		if self.debug:
			longest = space
			for i in range(len(lst)):
				for j in range(len(lst[i])):
					longest = max(longest, len(str(lst[i][j])))
			for i in range(len(lst)):
				for j in range(len(lst[i])):
					print("logger:", " "*(longest-len(str(lst[i][j])))+str(lst[i][j]), end=sep)
				print()

def main():
	h, w = map(int, sys.stdin.readline().split())
	s = [list(sys.stdin.readline().rstrip())[::-1] for i in [0]*h][::-1]
	cost = [[0]*w for i in [0]*h]
	for y in range(h):
		for x in range(w):
			if y == 0 and x == 0:
				if s[y][x] == "
					cost[y][x] = 1
			elif y == 0:
				if s[y][x] == "
					cost[y][x] = cost[y][x-1] + 1
				else:
					cost[y][x] = cost[y][x-1]
			elif x == 0:
				if s[y][x] == "
					cost[y][x] = cost[y-1][x] + 1
				else:
					cost[y][x] = cost[y-1][x]
			else:
				if s[y][x] == "
					cost[y][x] = cost[y-1][x] + 1
				else:
					cost[y][x] = cost[y-1][x]
				if s[y][x] == "
					cost[y][x] = min(cost[y][x], cost[y][x-1] + 1)
				else:
					cost[y][x] = min(cost[y][x], cost[y][x-1])
	logger = Logger(0)
	logger.print(h, w)
	print(cost[h-1][w-1])

main()

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

dp = [[float('inf') for _ in range(w)] for _ in range(h)]
if field[0][0] == '
    dp[0][0] = 1
else:
    dp[0][0] = 0

for i in range(h):
    for j in range(w):
        for di, dj in ((1, 0), (0, 1)):
            next_i = i + di
            next_j = j + dj
            if next_i >= h or next_j >= w:
                continue
            if field[i][j] == '.' and field[next_i][next_j] == '
                dp[next_i][next_j] = min(dp[next_i][next_j], dp[i][j] + 1)
            else:
                dp[next_i][next_j] = min(dp[next_i][next_j], dp[i][j])

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

Solution (Python):


import sys

sys.setrecursionlimit(10 ** 6)

class Logger:
	def __init__(self, is_debug):
		self.debug = is_debug
	def print(self, *arg):
		if self.debug:
			print("logger:", *arg)
	def plane(self, lst, sep=" ", space=0):
		if self.debug:
			longest = space
			for i in range(len(lst)):
				for j in range(len(lst[i])):
					longest = max(longest, len(str(lst[i][j])))
			for i in range(len(lst)):
				for j in range(len(lst[i])):
					print("logger:", " "*(longest-len(str(lst[i][j])))+str(lst[i][j]), end=sep)
				print()

def main():
	h, w = map(int, sys.stdin.readline().split())
	s = [list(sys.stdin.readline().rstrip())[::-1] for i in [0]*h][::-1]
	cost = [[0]*w for i in [0]*h]
	for y in range(h):
		for x in range(w):
			if y == 0 and x == 0:
				if s[y][x] == "
					cost[y][x] = 1
			elif y == 0:
				if s[y][x] == "
					cost[y][x] = cost[y][x-1] + 1
				else:
					cost[y][x] = cost[y][x-1]
			elif x == 0:
				if s[y][x] == "
					cost[y][x] = cost[y-1][x] + 1
				else:
					cost[y][x] = cost[y-1][x]
			else:
				if s[y][x] == "
					cost[y][x] = cost[y-1][x] + 1
				else:
					cost[y][x] = cost[y-1][x]
				if s[y][x] == "
					cost[y][x] = min(cost[y][x], cost[y][x-1] + 1)
				else:
					cost[y][x] = min(cost[y][x], cost[y][x-1])
	logger = Logger(0)
	logger.print(h, w)
	print(cost[h-1][w-1])

main()

Solution (Python):


import sys

sys.setrecursionlimit(10 ** 6)

class Logger:
	def __init__(self, is_debug):
		self.debug = is_debug
	def print(self, *arg):
		if self.debug:
			print("logger:", *arg)
	def plane(self, lst, sep=" ", space=0):
		if self.debug:
			longest = space
			for i in range(len(lst)):
				for j in range(len(lst[i])):
					longest = max(longest, len(str(lst[i][j])))
			for i in range(len(lst)):
				for j in range(len(lst[i])):
					print("logger:", " "*(longest-len(str(lst[i][j])))+str(lst[i][j]), end=sep)
				print()

def main():
	h, w = map(int, sys.stdin.readline().split())
	s = [list(sys.stdin.readline().rstrip())[::-1] for i in [0]*h][::-1]
	cost = [[0]*w for i in [0]*h]
	for y in range(h):
		for x in range(w):
			if y == 0 and x == 0:
				if s[y][x] == "
					cost[y][x] = 1
			elif y == 0:
				if s[y][x] == "
					cost[y][x] = cost[y][x-1] + 1
				else:
					cost[y][x] = cost[y][x-1]
			elif x == 0:
				if s[y][x] == "
					cost[y][x] = cost[y-1][x] + 1
				else:
					cost[y][x] = cost[y-1][x]
			else:
				if s[y][x] == "
					cost[y][x] = cost[y-1][x] + 1
				else:
					cost[y][x] = cost[y-1][x]
				if s[y][x] == "
					cost[y][x] = min(cost[y][x], cost[y][x-1] + 1)
				else:
					cost[y][x] = min(cost[y][x], cost[y][x-1])
	logger = Logger(0)
	logger.print(h, w)
	print(cost[h-1][w-1])

main()

Solution (Python):
h, w = map(int, input().split())
s = [] 
for i in range(h):
    s += [','.join(input()).split(',')]

cost = [[10000 for i in range(w)] for j in range(h)]


for hh in range(h):
    for ww in range(w):
        
        if hh == ww == 0:
            cost[0][0] = 0 if s[0][0] == '.' else 1

        if hh < h - 1:
            if s[hh][ww] == '.' and s[hh + 1][ww] == '
                cost[hh + 1][ww] = min(cost[hh][ww] + 1, cost[hh + 1][ww])
            else:
                cost[hh + 1][ww] = min(cost[hh][ww], cost[hh + 1][ww])
        if ww < w - 1:
            if s[hh][ww] == '.' and s[hh][ww + 1] == '
                cost[hh][ww + 1] = min(cost[hh][ww] + 1, cost[hh][ww + 1])
            else:
                cost[hh][ww + 1] = min(cost[hh][ww], cost[hh][ww + 1])

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

Solution (Python):



import sys
sys.setrecursionlimit(10**6)
readline = sys.stdin.readline
read = sys.stdin.read

h,w = [int(i) for i in readline().split()]
b = [readline().strip() for _ in range(h)]

INF = 10**9

dp0 = [[INF]*w for _ in range(h)]


if b[-1][-1] == "
    dp0[-1][-1] = 1

else:
    dp0[-1][-1] = 0


for i in range(h-1,-1,-1):
    for j in range(w-1,-1,-1):
        if b[i][j] == "
            r = INF
            if i != h-1: r = min(r,dp0[i+1][j] + (1 if b[i+1][j]=="." else 0))
            if j != w-1: r = min(r,dp0[i][j+1] + (1 if b[i][j+1]=="." else 0))
            
            dp0[i][j] = min(dp0[i][j],r)
            
        else:
            r = INF
            if i != h-1: r = min(r,dp0[i+1][j])
            if j != w-1: r = min(r,dp0[i][j+1])
            dp0[i][j] = min(dp0[i][j],r)
            





print(dp0[0][0])

Solution (Python):



import sys
sys.setrecursionlimit(10**6)
readline = sys.stdin.readline
read = sys.stdin.read

h,w = [int(i) for i in readline().split()]
b = [readline().strip() for _ in range(h)]

INF = 10**9

dp0 = [[INF]*w for _ in range(h)]


if b[-1][-1] == "
    dp0[-1][-1] = 1

else:
    dp0[-1][-1] = 0


for i in range(h-1,-1,-1):
    for j in range(w-1,-1,-1):
        if b[i][j] == "
            r = INF
            if i != h-1: r = min(r,dp0[i+1][j] + (1 if b[i+1][j]=="." else 0))
            if j != w-1: r = min(r,dp0[i][j+1] + (1 if b[i][j+1]=="." else 0))
            
            dp0[i][j] = min(dp0[i][j],r)
            
        else:
            r = INF
            if i != h-1: r = min(r,dp0[i+1][j])
            if j != w-1: r = min(r,dp0[i][j+1])
            dp0[i][j] = min(dp0[i][j],r)
            





print(dp0[0][0])

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

inf=float("inf")
ans=[[inf]*W for _ in range(H)]

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

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

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

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

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

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

if S[0][0]==S[-1][-1] and S[0][0]==".":
    print(dp[-1][-1]//2)
elif S[0][0]==S[-1][-1] and S[0][0]=="
    print(dp[-1][-1]//2+1)
else:
    print((dp[-1][-1]+1)//2)

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)]
d=[ [i+j for i in range(W)] for j in range(H)]

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  garden[i+di][j+dj]==color:
            d[i+di][j+dj]=min(d[i+di][j+dj],d[i][j])

        elif i+di<H and j+dj< W:
            d[i+di][j+dj]=min(d[i+di][j+dj],d[i][j]+1)

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, math, itertools, collections, bisect
input = lambda: sys.stdin.buffer.readline().rstrip().decode('utf-8')
inf = float('inf') ;mod = 10**9+7
mans = inf ;ans = 0 ;count = 0 ;pro = 1

dydx4 = ((-1,0),(0,-1),(0,1),(1,0))
h,w = map(int,input().split())
S = [input() for i in range(h)]
dp = [[inf]*w for i in range(h)]
if S[0][0] == "
else: dp[0][0] = 0
for i in range(h):
  for j in range(w):
    if i-1 >= 0:
      if S[i-1][j] == "." and S[i][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 j-1 >= 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[h-1][w-1])

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

dp=[[10**9]*w for i in range(h)]
if a[0][0]==".":
    dp[0][0]=0
else:
    dp[0][0]=1
    
for i in range(h):
    for j in range(w):
        if i!=0:
            if a[i-1][j]=="." and a[i][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 j!=0:
            if a[i][j-1]=="." and a[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):
from itertools import product
from heapq import heappush, heappop

class Dijkstra:
    def __init__(self, N):
        self.N = N 
        self.E = [[] for _ in range(N)]

    def add_edge(self, init, end, weight, undirected=False):
        self.E[init].append((end, weight))
        if undirected: self.E[end].append((init, weight))
    
    def distance(self, s):
        INF = float('inf')
        self.dist = [INF] * self.N 
        self.prev = [-1] * self.N 
        n_visited = 0 
        heap = []
        heappush(heap, (0, -1, s))
        while heap:
            d, p, v = heappop(heap)
            if self.dist[v] != INF: continue 
            self.dist[v] = d; self.prev[v] = p
            n_visited += 1
            if n_visited == self.N: break
            for u, c in self.E[v]:
                if self.dist[u] != INF: continue
                temp = d + c
                if self.dist[u] > temp: heappush(heap, (temp, v, u))
        return self.dist
    
    def shortest_path(self, t):
        P = []
        prev = self.prev
        while True:
            P.append(t)
            t = prev[t]
            if t == -1: break
        return P[::-1]

H, W = map(int, input().split())
dijkstra = Dijkstra(H * W)

def vtx(i, j): return i*W + j
def coord(n): return divmod(n, W)

grid = [input() for _ in range(H)] 
E = [[] for _ in range(H * W)]
ans = 0 if grid[0][0] == '.' else 1
for i, j in product(range(H), range(W)):
    v = vtx(i, j)
    check = [vtx(i+dx, j+dy) for dx, dy in [(1, 0), (0, 1)] if i+dx <= H-1 and j+dy <= W-1]
    for u in check:
        x, y = coord(u)
        if grid[i][j] == '.' and grid[x][y] == '
            dijkstra.add_edge(v, u, 1)
        else:
            dijkstra.add_edge(v, u, 0)
dist = dijkstra.distance(0)
ans += dist[vtx(H-1, W-1)]
print(ans)

Solution (Python):
from itertools import product

class BellmanFord:
    def __init__(self, N):
        self.N = N 
        self.E = [[] for _ in range(N)]

    def add_edge(self, init, end, weight, undirected=False):
        self.E[init].append((end, weight))
        if undirected: self.E[end].append((init, weight))
    
    def distance(self, s):
        INF = float('inf')
        self.dist = [INF] * self.N 
        self.prev = [-1] * self.N 
        self.dist[s] = 0
        for _ in range(self.N):
            updated = False
            for v in range(self.N):
                d = self.dist[v]
                if d == INF: continue
                for u, c in self.E[v]:
                    temp = d + c
                    if self.dist[u] > temp:
                        updated = True
                        self.dist[u] = temp
                        self.prev[u] = v
            if not updated: break 
        else: return None 
        return self.dist
    
    def shortest_path(self, t):
        P = []
        prev = self.prev
        while True:
            P.append(t)
            t = prev[t]
            if t == -1: break
        return P[::-1]

H, W = map(int, input().split())
bf = BellmanFord(H * W)

def vtx(i, j): return i*W + j
def coord(n): return divmod(n, W)

grid = [input() for _ in range(H)] 
E = [[] for _ in range(H * W)]
ans = 0 if grid[0][0] == '.' else 1
for i, j in product(range(H), range(W)):
    v = vtx(i, j)
    check = [vtx(i+dx, j+dy) for dx, dy in [(1, 0), (0, 1)] if i+dx <= H-1 and j+dy <= W-1]
    for u in check:
        x, y = coord(u)
        if grid[i][j] == '.' and grid[x][y] == '
            bf.add_edge(v, u, 1)
        else:
            bf.add_edge(v, u, 0)
dist = bf.distance(0)
ans += dist[vtx(H-1, W-1)]
print(ans)

Solution (Python):
from itertools import product

class BellmanFord:
    def __init__(self, N):
        self.N = N 
        self.E = [[] for _ in range(N)]

    def add_edge(self, init, end, weight, undirected=False):
        self.E[init].append((end, weight))
        if undirected: self.E[end].append((init, weight))
    
    def distance(self, s):
        INF = float('inf')
        self.dist = [INF] * self.N 
        self.prev = [-1] * self.N 
        self.dist[s] = 0
        for _ in range(self.N):
            updated = False
            for v in range(self.N):
                d = self.dist[v]
                if d != INF:
                    for u, c in self.E[v]:
                        temp = d + c
                        if self.dist[u] > temp:
                            updated = True
                            self.dist[u] = temp
                            self.prev[u] = v
            if not updated: break 
        else: return None 
        return self.dist
    
    def shortest_path(self, t):
        P = []
        prev = self.prev
        while True:
            P.append(t)
            t = prev[t]
            if t == -1: break
        return P[::-1]

H, W = map(int, input().split())
bf = BellmanFord(H * W)

def vtx(i, j): return i*W + j
def coord(n): return divmod(n, W)

grid = [input() for _ in range(H)] 
E = [[] for _ in range(H * W)]
ans = 0 if grid[0][0] == '.' else 1
for i, j in product(range(H), range(W)):
    v = vtx(i, j)
    check = [vtx(i+dx, j+dy) for dx, dy in [(1, 0), (0, 1)] if i+dx <= H-1 and j+dy <= W-1]
    for u in check:
        x, y = coord(u)
        if grid[i][j] == '.' and grid[x][y] == '
            bf.add_edge(v, u, 1)
        else:
            bf.add_edge(v, u, 0)
dist = bf.distance(0)
ans += dist[vtx(H-1, W-1)]
print(ans)

Solution (Python):
from itertools import product
from collections import deque

class ZeroOneBFS:
    def __init__(self, N):
        self.N = N 
        self.E = [[] for _ in range(N)]
        
    def add_edge(self, init, end, weight, undirected=False):
        assert weight in [0, 1]
        self.E[init].append((end, weight))
        if undirected: self.E[end].append((init, weight))
        
    def distance(self, s):
        INF = float('inf')
        self.dist = [INF] * self.N 
        self.prev = [-1] * self.N 
        visited = [False] * self.N
        dq = deque([(0, -1, s)]) 
        n_visited = 0 
        while dq:
            d, p, v = dq.popleft()
            if visited[v]: continue 
            self.dist[v] = d; self.prev[v] = p; visited[v] = True
            n_visited += 1
            if n_visited == self.N: break
            for u, c in self.E[v]:
                if visited[u]: continue
                if c == 0: dq.appendleft((d, v, u))
                else: dq.append((d + 1, v, u))
        return self.dist
    
    def shortest_path(self, t):
        P = []
        prev = self.prev
        while True:
            P.append(t)
            t = prev[t]
            if t == -1: break
        return P[::-1]

H, W = map(int, input().split())
zobfs = ZeroOneBFS(H * W)
 
def vtx(i, j): return i*W + j
def coord(n): return divmod(n, W)
 
grid = [input() for _ in range(H)] 
E = [[] for _ in range(H * W)]
ans = 0 if grid[0][0] == '.' else 1
for i, j in product(range(H), range(W)):
    v = vtx(i, j)
    check = [vtx(i+dx, j+dy) for dx, dy in [(1, 0), (0, 1)] if i+dx <= H-1 and j+dy <= W-1]
    for u in check:
        x, y = coord(u)
        if grid[i][j] == '.' and grid[x][y] == '
            zobfs.add_edge(v, u, 1)
        else:
            zobfs.add_edge(v, u, 0)
dist = zobfs.distance(0)
ans += dist[vtx(H-1, W-1)]
print(ans)

Solution (Python):
from itertools import product
from heapq import heappush, heappop

class Dijkstra:
    def __init__(self, N):
        self.N = N 
        self.E = [[] for _ in range(N)]

    def add_edge(self, init, end, weight, undirected=False):
        self.E[init].append((end, weight))
        if undirected: self.E[end].append((init, weight))
    
    def distance(self, s):
        INF = float('inf')
        self.dist = [INF] * self.N 
        self.prev = [-1] * self.N 
        visited = [False] * self.N
        n_visited = 0 
        heap = []
        heappush(heap, (0, -1, s))
        while heap:
            d, p, v = heappop(heap)
            if visited[v]: continue 
            self.dist[v] = d; self.prev[v] = p; visited[v] = True
            n_visited += 1
            if n_visited == self.N: break
            for u, c in self.E[v]:
                if visited[u]: continue
                temp = d + c
                if self.dist[u] > temp: heappush(heap, (temp, v, u))
        return self.dist
    
    def shortest_path(self, t):
        P = []
        prev = self.prev
        while True:
            P.append(t)
            t = prev[t]
            if t == -1: break
        return P[::-1]

H, W = map(int, input().split())
dijkstra = Dijkstra(H * W)

def vtx(i, j): return i*W + j
def coord(n): return divmod(n, W)

grid = [input() for _ in range(H)] 
E = [[] for _ in range(H * W)]
ans = 0 if grid[0][0] == '.' else 1
for i, j in product(range(H), range(W)):
    v = vtx(i, j)
    check = [vtx(i+dx, j+dy) for dx, dy in [(1, 0), (0, 1)] if i+dx <= H-1 and j+dy <= W-1]
    for u in check:
        x, y = coord(u)
        if grid[i][j] == '.' and grid[x][y] == '
            dijkstra.add_edge(v, u, 1)
        else:
            dijkstra.add_edge(v, u, 0)
dist = dijkstra.distance(0)
ans += dist[vtx(H-1, W-1)]
print(ans)

Solution (Python):
from itertools import product
from heapq import heappush, heappop

class Dijkstra:
    def __init__(self, N):
        self.N = N 
        self.E = [[] for _ in range(N)]

    def add_edge(self, init, end, weight, undirected=False):
        self.E[init].append((end, weight))
        if undirected: self.E[end].append((init, weight))
    
    def distance(self, s):
        INF = float('inf')
        self.dist = [INF] * self.N 
        self.prev = [-1] * self.N 
        rem = self.N 
        heap = []
        heappush(heap, (0, -1, s))
        while heap and rem:
            d, p, v = heappop(heap)
            if d >= self.dist[v]: continue 
            self.dist[v] = d; self.prev[v] = p
            rem -= 1
            for u, c in self.E[v]:
                temp = d + c
                if self.dist[u] > temp: heappush(heap, (temp, v, u))
        return self.dist

H, W = map(int, input().split())
dijkstra = Dijkstra(H * W)

def vtx(i, j): return i*W + j
def coord(n): return divmod(n, W)

grid = [input() for _ in range(H)] 
E = [[] for _ in range(H * W)]
ans = 0 if grid[0][0] == '.' else 1
for i, j in product(range(H), range(W)):
    v = vtx(i, j)
    check = [vtx(i+dx, j+dy) for dx, dy in [(1, 0), (0, 1)] if i+dx <= H-1 and j+dy <= W-1]
    for u in check:
        x, y = coord(u)
        if grid[i][j] == '.' and grid[x][y] == '
            dijkstra.add_edge(v, u, 1)
        else:
            dijkstra.add_edge(v, u, 0)
dist = dijkstra.distance(0)
ans += dist[vtx(H-1, W-1)]
print(ans)

Solution (Python):
n,m=map(int,input().split())
s=[list(input()) for i in range(n)]
ans=[[10**9+7]*m for i in range(n)]
ans[0][0]=int(s[0][0]=='
for i in range(n):
    for j in range(m):
        if i>0:
            
            ans[i][j]=min(ans[i][j],ans[i-1][j]+int(s[i-1][j]=='.'and s[i][j]=='
        if j>0:
            ans[i][j]=min(ans[i][j],ans[i][j-1]+int(s[i][j-1]=='.' and s[i][j]=='
print(ans[n-1][m-1])

Solution (Python):
from itertools import product
from collections import deque

class ZeroOneBFS:
    def __init__(self, N):
        self.N = N
        self.E = [[] for _ in range(N)]
        
    def add_edge(self, init, end, weight, undirected=False):
        assert weight in [0, 1]
        self.E[init].append((end, weight))
        if undirected: self.E[end].append((init, weight))
        
    def distance(self, s):
        self.order = [-1] * self.N 
        self.dist = [-1] * self.N 
        dq = deque([(s, 0)]) 
        num = 0 
        while dq:
            v, d = dq.popleft()
            if self.order[v] < 0: 
                self.order[v] = num; self.dist[v] = d
                num += 1
                for u, w in self.E[v]:
                    if self.order[u] >= 0: continue
                    if w == 0: dq.appendleft((u, d))
                    else: dq.append((u, d+1))
        return self.order, self.dist

H, W = map(int, input().split())
zobfs = ZeroOneBFS(H * W)

def vtx(i, j): return i*W + j
def coord(n): return divmod(n, W)

grid = [input() for _ in range(H)] 
E = [[] for _ in range(H * W)]
ans = 0 if grid[0][0] == '.' else 1
for i, j in product(range(H), range(W)):
    v = vtx(i, j)
    check = [vtx(i+dx, j+dy) for dx, dy in [(1, 0), (0, 1)] if i+dx <= H-1 and j+dy <= W-1]
    for u in check:
        x, y = coord(u)
        if grid[i][j] == '.' and grid[x][y] == '
            zobfs.add_edge(v, u, 1)
        else:
            zobfs.add_edge(v, u, 0)
_, dist = zobfs.distance(0)
ans += dist[vtx(H-1, W-1)]
print(ans)

Solution (Python):
h,w = map(int,input().split())
s = [input() for _ in range(h)]
dp = [[float("inf") for _ in range(w)] for _ in range(h)]
dp[0][0] = 0 if s[0][0] == "." else 1 
for i in range(h):
    for j in range(w):
        if i < h-1:
            if s[i][j] == "." and s[i+1][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])
        if j < w-1:
            if s[i][j] == "." and s[i][j+1] == "
                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])
print(dp[h-1][w-1])