Problem:


Score : 400 points

Problem Statement

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

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

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

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

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

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

Constraints

2 \leq H, W \leq 100

Input

Input is given from Standard Input in the following format:

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

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

Output

Print the minimum number of operations needed.

Sample Input 1

3 3
.##
.#.
##.

Sample Output 1

1

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

Sample Input 2

2 2
#.
.#

Sample Output 2

2

Sample Input 3

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

Sample Output 3

0

No operation may be needed.

Sample Input 4

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

Sample Output 4

4



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


Sample output:
1

Submission status: Accepted

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


def solve(H: int, W: int, s: "List[str]"):
    dp = [[0 for w in range(W)] for h in range(H)] # dp[h][w]はh,wに達するための回数
    if s[0][0] == '#':
        dp[0][0] = 1

    for w in range(W-1): # 0行目について
        if s[0][w+1] == '.': # 移動先が白だったら特に変わりなし
            dp[0][w+1] = dp[0][w]
        elif s[0][w] == '.' and s[0][w+1] == '#': # 移動元が白で先が黒ならば、新しく施行1回追加
            dp[0][w+1] = dp[0][w] + 1
        elif s[0][w] == '#' and s[0][w+1] == '#': # 移動元も先も黒だったとしたら、試行回数は変わらない
            dp[0][w+1] = dp[0][w]

    for h in range(H-1): # 1列目について
        if s[h+1][0] == '.':
            dp[h+1][0] = dp[h][0]
        elif s[h][0] == '.' and s[h+1][0] == '#':
            dp[h+1][0] = dp[h][0] + 1
        elif s[h][0] == '#' and s[h+1][0] == '#':
            dp[h+1][0] = dp[h][0]

    for h in range(1, H):
        for w in range(W-1):
            if s[h][w+1] == '.':
                dp[h][w+1] = min(dp[h][w], dp[h-1][w+1])
            elif s[h][w] == '.' and s[h][w+1] == '#':
                if s[h-1][w+1] == '.':
                    dp[h][w+1] = min(dp[h][w]+1, dp[h-1][w+1]+1)
                elif s[h-1][w+1] == '#':
                    dp[h][w+1] = min(dp[h][w]+1, dp[h-1][w+1])
            elif s[h][w] == '#' and s[h][w+1] == '#':
                if s[h-1][w+1] == '.':
                    dp[h][w+1] = min(dp[h][w], dp[h-1][w+1]+1)
                elif s[h-1][w+1] == '#':
                    dp[h][w+1] = min(dp[h][w], dp[h-1][w+1])
    print(dp[H-1][W-1])
    return


# Generated by 1.1.7.1 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    H = int(next(tokens))  # type: int
    W = int(next(tokens))  # type: int
    s = [next(tokens) for _ in range(H)]  # type: "List[str]"
    solve(H, W, s)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys

readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
read = sys.stdin.buffer.read
sys.setrecursionlimit(10 ** 7)
INF = float('inf')

H, W = map(int, readline().split())
masu = []
for _ in range(H):
    masu.append(readline().rstrip().decode('utf-8'))
# print(masu)

dp = [[INF]*W for _ in range(H)]
dp[0][0] = int(masu[0][0] == "#")

dd = [(1, 0), (0, 1)]

# 配るDP
for i in range(H):
    for j in range(W):
        for dx, dy in dd:
            ni = i + dy
            nj = j + dx
            # はみ出す場合
            if (ni >= H or nj >= W):
                continue
            add = 0
            if masu[ni][nj] == "#" and masu[i][j] == ".":
                add = 1
            dp[ni][nj] = min(dp[ni][nj], dp[i][j] + add)
# print(dp)
ans = dp[H-1][W-1]
print(ans)

Submission status: Accepted

Solution code:
#AGC043-A
h,w = map(int,input().split())
grid = [input() for _ in range(h)]

dp = [[1000]*w for _ in range(h)]
dp[0][0] = 1 if grid[0][0] == "#" else 0
#進む前の相対位置
d = [(-1, 0), (0, -1)]

for i in range(h):
    for j in range(w):
        if i == 0 and j == 0:
            pass
        else:
            tmp = 1000
            for k in d:
                bx,by = j+k[0],i+k[1]
                if 0 <= bx <w and 0 <= by < h:
                    if grid[i][j] == '#' and grid[by][bx] == '.':
                        tmp = dp[by][bx] + 1
                    else:
                        tmp = dp[by][bx]
                dp[i][j] = min(dp[i][j],tmp)
                
print(dp[-1][-1])

Submission status: Accepted

Solution code:
from collections import deque
printn = lambda x: print(x,end='')
inn = lambda : int(input())
inl   = lambda: list(map(int, input().split()))
inm   = lambda:      map(int, input().split())
ins = lambda : input().strip()
DBG = True # and False
BIG = 10**7
R = 10**9 + 7

def ddprint(x):
  if DBG:
    print(x)

h,w = inm()
s = []
for i in range(h):
    s.append(ins())
d = [[BIG]*w for i in range(h)]
z = 1 if s[0][0]=='#' else 0
q = deque([(0,0,z)])
while len(q)>0:
    x,y,z = q.popleft()
    #ddprint(f"1 {x=} {y=} {z=} {d=}")
    if z>=d[x][y]:
        continue
    #ddprint(d[x])
    d[x][y] = z
    incx = 1 if x<h-1 and s[x+1][y]=='#' and s[x][y]=='.' else 0
    incy = 1 if y<w-1 and s[x][y+1]=='#' and s[x][y]=='.' else 0
    if x<h-1 and d[x+1][y]>z+incx:
        q.append((x+1,y,z+incx))
    if y<w-1 and d[x][y+1]>z+incy:
        q.append((x,y+1,z+incy))
print(d[h-1][w-1])

Submission status: Accepted

Solution code:
def main():
  import sys
  input=sys.stdin.buffer.readline
  h,w=map(int,input().split())
  b,q=b'.'*w,range(w)
  for i in range(h):
    s=input()
    a=[]
    a_add=a.append
    for x,y,z,c in zip(b,b'.'+s,s,q):
      if x==46>z:c+=1
      if y==46>z:i+=1
      if i>c:i=c
      a_add(i)
    b,q=s,a
  print(i)
main()

Submission status: Accepted

Solution code:
h, w = map(int, input().split())
s = [list(input()) for i in range(h)]
dp = [[float("inf")] * w for i in range(h)]
dp[0][0] = 1 if s[0][0] == "#" else 0
d = [(-1, 0), (0, -1)]
for i in range(h):
    for j in range(w):
        if i == 0 and j == 0:
            pass
        else:
            m = float("inf")
            for k in d:
                x = i + k[0]
                y = j + k[1]
                if 0 <= x < h and 0 <= y < w:
                    if s[i][j] == "#" and s[x][y] == ".":
                        m = dp[x][y] + 1
                    else:
                        m = dp[x][y]
                dp[i][j] = min(dp[i][j], m)
print(dp[h - 1][w - 1])

Submission status: Accepted

Solution code:
# A - Range Flip Find Route
H,W = map(int,input().split())
INF = 1000000
s = [input() for _ in range(H)]
a = [[INF]*(W+1) for _ in range(H+1)]
for i in range(1,H+1):
    for j in range(1,W+1):
        if (i,j)==(1,1):
            a[i][j] = int(s[0][0]=='#')
        elif i==1:
            a[i][j] = a[i][j-1]+int(s[i-1][j-2]=='.' and s[i-1][j-1]=='#')
        elif j==1:
            a[i][j] = a[i-1][j]+int(s[i-2][j-1]=='.' and s[i-1][j-1]=='#')
        else:
            a[i][j] = min(
                a[i][j-1]+int(s[i-1][j-2]=='.' and s[i-1][j-1]=='#'),
                a[i-1][j]+int(s[i-2][j-1]=='.' and s[i-1][j-1]=='#')
            )
print(a[H][W])

Submission status: Accepted

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

inf = 10**18
# dp[i][j]はi.j点に行くまでに何回白→黒の変化があったか
dp = [[inf] * W for _ in range(H)]
if grid[0][0] == "#":
    dp[0][0] = 1
else:
    dp[0][0] = 0

for i in range(H):
    for j in range(W):
        if i != 0: # 下移動
            # 今いてるのがi,j点、前の点(上)が白で次が黒なら1足す
            tmp = dp[i - 1][j] + int(grid[i][j]=="#" and grid[i - 1][j]==".")
            dp[i][j] = min(dp[i][j], tmp)
        if j != 0: # 右移動
            # 前の点(左)が白で次が黒なら1足す
            tmp = dp[i][j - 1] + int(grid[i][j]=="#" and grid[i][j - 1]==".")
            dp[i][j] = min(dp[i][j], tmp)
        # この一連の処理で、i,j点に、下移動した場合と右移動した場合のうちの最小値が得られる。
# こたえは目的地, i.e. 右下の点のdpの値
ans = dp[H - 1][W - 1]
print(ans)

Submission status: Accepted

Solution code:
def read_int():
    return int(input())


def read_ints():
    return map(int, input().split(' '))


r, c = read_ints()
s = []
for i in range(r):
    s.append(input())
inf = int(1e9)
dp = [[inf for j in range(c)] for i in range(r)]
dp[0][0] = 1 if s[0][0] == '#' else 0
for i in range(r):
    for j in range(c):
        if i > 0:
            dp[i][j] = dp[i - 1][j]
            if s[i][j] == '#' and s[i - 1][j] == '.':
                dp[i][j] += 1
        if j > 0:
            another = dp[i][j - 1]
            if s[i][j] == '#' and s[i][j - 1] == '.':
                another += 1
            dp[i][j] = min(dp[i][j], another)
print(dp[r - 1][c - 1])

Submission status: Accepted

Solution code:
_,*s=open(0);t="."
b=t*101;q=range(101);i=0
for s in s:
 a=[i];i+=1
 for x,y,z,c in zip(b,t+s,s,q):a+=min(c+(t>z<x),a[-1]+(t>z<y)),
 b,q=s,a[1:]
print(a[-2])

Submission status: Accepted

Solution code:
_,*s=open(0);t=".";b=t*101;q=range(101);i=0
for s in s:
 a=[i];i+=1
 for x,y,z,c in zip(b,t+s,s,q):a+=min(c+(t==x>z),a[-1]+(t==y>z)),
 b,q=s,a[1:]
print(a[-2])

Submission status: Accepted

Solution code:
_,*s=open(0)
t='.'
b=t*101
q=range(101)
i=0
for s in s:
 a=[i];i+=1
 for x,y,z,c in zip(b,t+s,s,q):a+=min(c+(x==t>z),a[-1]+(y==t>z)),
 b,q=s,a[1:]
print(a[-2])

Submission status: Accepted

Solution code:
_,*s=open(0);t='.';b=t*101;q=range(101);i=0
for s in s:
 a=[i];i+=1
 for x,y,z,c in zip(b,t+s,s,q):a+=min(c+(x==t>z),a[-1]+(y==t>z)),
 b,q=s,a[1:]
print(a[-2])

Submission status: Accepted

Solution code:
_,*s=open(0)
t='.'
b=t*101
r=range(101)
i=0
for s in s:
 a=[i];i+=1
 for x,y,z,c in zip(b,t+s,s,r):a+=min(c+(t>z<x),a[-1]+(t>z<y)),
 b,r=s,a[1:]
print(a[-2])

Submission status: Accepted

Solution code:
_,*s=open(0)
t="."
b=t*101
q=range(101)
i=0
for s in s:
 a=[i];i+=1
 for x,y,z,c in zip(b,t+s,s,q):a+=min(c+(t>z<x),a[-1]+(t>z<y)),
 b,q=s,a[1:]
print(a[-2])

Submission status: Accepted

Solution code:
h,w = map(int, input().split())
L = [input() for i in range(h)]
dp = [[10**9]*w for i in range(h)]
if L[0][0] == ".":
    dp[0][0] = 0
else:
    dp[0][0] = 1

li = ((1,0),(0,1))
for i in range(h):
    for j in range(w):
        for dy,dx in li:
            ny,nx = i+dy,j+dx
            if ny >= h or nx >= w:
                continue
            plus = 0
            if L[i][j] == "." and L[ny][nx] == "#":
                plus =1
            dp[ny][nx] = min(dp[i][j]+plus,dp[ny][nx])
            
print(dp[h-1][w-1])

Submission status: Accepted

Solution code:
h, w = map(int, input().split())
L = [str(input()) for _ in range(h)]
dp = [[float('inf')] * w for _ in range(h)]
dp[0][0] = 1 if L[0][0] =='#' else 0
for i in range(h):
    for j in range(w):
        if L[i][j] == '.':
            if i < h - 1:
                dp[i+1][j] = min(dp[i+1][j], dp[i][j] if L[i+1][j] == '.' else dp[i][j] + 1)
            if j < w - 1:
                dp[i][j+1] = min(dp[i][j+1], dp[i][j] if L[i][j+1] == '.' else dp[i][j] + 1)
        else:
            if i < h - 1:
                dp[i+1][j] = min(dp[i+1][j], dp[i][j])
            if j < w - 1:
                dp[i][j+1] = min(dp[i][j+1], dp[i][j])
print(dp[h-1][w-1])

Submission status: Accepted

Solution code:
h,w=map(int,input().split())
s=[]
for _ in range(h):
    s.append(list(input()))
a=[[0]]
for i in range(1,h):
    t=a[i-1][0]
    if s[i][0]!=s[i-1][0]:
        a.append([t+1])
    else:
        a.append([t])

for j in range(1,w):
    t=a[0][j-1]
    if s[0][j]!=s[0][j-1]:
        a[0].append(t+1)
    else:
        a[0].append(t)

for i in range(1,h):
    for j in range(1,w):
        up=a[i-1][j]
        left=a[i][j-1]
        if s[i][j]!=s[i-1][j]:
            up += 1
        if s[i][j]!=s[i][j-1]:
            left += 1
        mn=min(up,left)
        a[i].append(mn)
num=a[h-1][w-1]
ans=(num+1)//2
if s[0][0]=='#' and num%2==0:
    ans += 1
print(ans)

Submission status: Accepted

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

dp = [[10001] * W for _ in range(H)]
if s[0][0] == '#':
    dp[0][0] = 1
else:
    dp[0][0] = 0
moves = [[1, 0],[0, 1]]

for y in range(H):
    for x in range(W):
        for m in moves:
            ny, nx = y+m[0], x+m[1]
            if ny >= H or nx >= W:
                continue
            add = 0
            # .から#に突入する時だけカウントが増える
            if s[y][x] == '.' and s[ny][nx] == '#':
                add = 1
            dp[ny][nx] = min(dp[ny][nx], dp[y][x] + add)
print(dp[-1][-1])

Submission status: Accepted

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

count = [[100000] * W for _ in range(W)]
count[0][0] = 0 if S[0][0] == "." else 1


for i in range(H):
    for j in range(W):
        if i + j == 0:
            continue
        X, Y = 10**6, 10**6
        if i > 0:
            if S[i][j] == "#" and S[i-1][j] == ".":
                X = count[i-1][j] + 1
            else:
                X = count[i-1][j]
        if j > 0:
            if S[i][j] == "#" and S[i][j-1] == ".":
                Y = count[i][j-1] + 1
            else:
                Y = count[i][j-1]
        count[i][j] = min(X, Y)

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

Submission status: Accepted

Solution code:
h, w = map(int, input().split())
s = [list(map(str, input().rstrip())) for _ in range(h)]

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

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

moves = [[1, 0], [0, 1]]

for y in range(h):
    for x in range(w):
        for m in moves:
            ny, nx = y + m[0], x + m[1]
            if ny >= h or nx >= w:
                continue
            add = 0
            # .から#に突入する時だけカウントが増える
            if s[y][x] == "." and s[ny][nx] == "#":
                add = 1
            dp[ny][nx] = min(dp[ny][nx], dp[y][x] + add)

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

Submission status: Accepted

Solution code:
from collections import deque

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

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

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

moves = [[1, 0], [0, 1]]

for y in range(h):
    for x in range(w):
        for m in moves:
            ny, nx = y + m[0], x + m[1]
            if ny >= h or nx >= w:
                continue
            add = 0
            # .から#に突入する時だけカウントが増える
            if s[y][x] == "." and s[ny][nx] == "#":
                add = 1
            dp[ny][nx] = min(dp[ny][nx], dp[y][x] + add)

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

Submission status: Accepted

Solution code:
H,W = list(map(int, input().split()))
B = []
for _ in range(H):
  B.append(input())
  
A = [[999999 for _ in range(W)] for _ in range(H)]
A[0][0] = 0 if B[0][0] == "." else 1

for i in range(H):
  for j in range(W):
    if i+j == 0:
      continue
    X,Y = 999999, 999999
    if i > 0:
      X = A[i-1][j] 
      X += 1 if B[i-1][j] == '.' and B[i][j] == '#' else 0
    if j > 0:
      Y = A[i][j-1]
      Y += 1 if B[i][j-1] == '.' and B[i][j] == '#' else 0
    A[i][j] = min(X,Y)
    
print(A[H-1][W-1])
#for i in range(H):
#  print(A[i])

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10**6)
from math import floor,ceil,sqrt,factorial,log

mod = 10 ** 9 + 7
inf = float('inf')
ninf = -float('inf')
 
#整数input
def ii(): return int(sys.stdin.readline().rstrip()) #int(input())
def mii(): return map(int,sys.stdin.readline().rstrip().split())
def limii(): return list(mii()) #list(map(int,input().split()))
def lin(n:int): return [ii() for _ in range(n)]
def llint(n: int): return [limii() for _ in range(n)]
#文字列input
def ss(): return sys.stdin.readline().rstrip() #input()
def mss(): return sys.stdin.readline().rstrip().split()
def limss(): return list(mss()) #list(input().split())
def lst(n:int): return [ss() for _ in range(n)]
def llstr(n: int): return [limss() for _ in range(n)]

#本当に貪欲法か？ DP法では？？
#本当に貪欲法か？ DP法では？？
#本当に貪欲法か？ DP法では？？

h,w=mii()

mat=[list(ss()) for _ in range(h)]

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

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

                    
print(chk[-1][-1])
#print(chk)

Submission status: Accepted

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

dp= [[float("inf") for _ in range(W)] for _ in range(H)]
dp[0][0]= 1 if s[0][0]=="#" else 0

mv=[(-1,0),(0,-1)]
for i in range(H):
  for j in range(W):
    if i==0 and j==0: pass
    else:
      tmp=float("inf")
      for k in mv:
        a = i+k[0]
        b = j+k[1]
        if 0 <=a <= H-1 and 0 <=b <= W-1:
          if s[i][j]=="#" and s[a][b]==".":
            tmp= dp[a][b]+1
          else:
            tmp= dp[a][b]
        dp[i][j]=min(dp[i][j],tmp)
        
print(dp[-1][-1])

Submission status: Accepted

Solution code:
h,w=map(int,input().split())
s=[['x']*(w+1)]
for i in range(h):
  tmp=['x']
  tmp.extend(list(input()))
  s.append(tmp)
dp=[[0]*(w+1) for _ in range(h+1)]
if s[1][1] == '#':
  dp[1][1] = 1
for i in range(2,h+1):
  if s[i][1] == s[i-1][1]:
    dp[i][1] = dp[i-1][1]
  else:
    if s[i][1] == '#':
      dp[i][1] = dp[i-1][1] + 1
    else:
      dp[i][1] = dp[i-1][1]
for i in range(2,w+1):
  if s[1][i] == s[1][i-1]:
    dp[1][i] = dp[1][i-1]
  else:
    if s[1][i] == '#':
      dp[1][i] = dp[1][i-1] + 1
    else:
      dp[1][i] = dp[1][i-1]
for i in range(2,h+1):
  for j in range(2,w+1):
    if s[i-1][j] == s[i][j] and s[i][j-1] == s[i][j]:
      dp[i][j] = min(dp[i-1][j],dp[i][j-1])
    elif s[i-1][j] != s[i][j] and s[i][j-1] == s[i][j]:
      if s[i][j] == '#':
        dp[i][j] = min(dp[i-1][j]+1,dp[i][j-1])
      else:
        dp[i][j] = min(dp[i-1][j],dp[i][j-1])
    elif s[i-1][j] == s[i][j] and s[i][j-1] != s[i][j]:
      if s[i][j] == '#':
        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:
      if s[i][j] == '#':
        dp[i][j] = min(dp[i-1][j]+1,dp[i][j-1]+1)
      else:
        dp[i][j] = min(dp[i-1][j],dp[i][j-1])    
print(dp[h][w])

Submission status: Accepted

Solution code:
def main():
    h, w = map(int, input().split())
    field = [list(input()) for _ in range(h)]
    dp = [[float('inf')] * w for _ in [0] * h]
    dp[0][0] = (field[0][0] == "#")

    for i in range(h):
        for j in range(w):
            if i > 0:
                dp[i][j] = min(dp[i][j], dp[i - 1][j] +
                               (field[i - 1][j] == "." and field[i][j] == "#"))
            if j > 0:
                dp[i][j] = min(dp[i][j], dp[i][j-1] +
                               (field[i][j - 1] == "." and field[i][j] == "#"))
    print(dp[-1][-1])

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
from queue import Queue

INF = 10 ** 9
dx = [1, 0]
dy = [0, 1]

h, w = map(int, input().split())
s = [input() for _ in range(h)]
dist = [[INF] * w for _ in range(h)]
dist[0][0] = 0

q = Queue()
sx, sy = 0, 0
q.put([0, 0])
while not q.empty():
    ux, uy = q.get()
    for k in range(2):
        vx = ux + dx[k]
        vy = uy + dy[k]
        if not (0 <= vx < h and 0 <= vy < w):
            continue
        cost = s[ux][uy] == "#" and s[vx][vy] == "."
        if dist[vx][vy] > dist[ux][uy] + cost:
            dist[vx][vy] = dist[ux][uy] + cost
            q.put([vx, vy])

print(dist[-1][-1] + (s[-1][-1] == "#"))

Submission status: Accepted

Solution code:
h,w = map(int,input().split())
s = [input() for _ in range(h)]
dp = [[float('inf')]*w for i in range(h)]
dp[0][0] = 1 if s[0][0]=='#' else 0
for x in range(h):
    for y in range(w):
        if x+1<h:
            a = 1 if s[x][y]=='.' and s[x+1][y]=='#' else 0
            dp[x+1][y] = min(dp[x][y]+a,dp[x+1][y])
        if y+1<w:
            a = 1 if s[x][y]=='.' and s[x][y+1]=='#' else 0
            dp[x][y+1] = min(dp[x][y]+a,dp[x][y+1])

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

Submission status: Accepted

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

dp = [[0]*w for _ in range(h)]
if mat[0][0] == "#":
    dp[0][0] = 1
for i in range(1, w):
    if mat[0][i] != mat[0][i-1] and mat[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 mat[j][0] != mat[j-1][0] and mat[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):
        ver = dp[i-1][j]
        hor = dp[i][j-1]
        if mat[i-1][j] != mat[i][j] and mat[i][j] == "#":
            ver += 1
        if mat[i][j-1] != mat[i][j] and mat[i][j] == "#":
            hor += 1
        dp[i][j] = min(ver, hor)
print(dp[h-1][w-1])

Submission status: Accepted

Solution code:
#dpでできないかな？
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**7)
from collections import Counter, deque
from collections import defaultdict
from itertools import combinations, permutations, accumulate, groupby, product
from bisect import bisect_left,bisect_right
from heapq import heapify, heappop, heappush
from math import floor, ceil,pi
from operator import itemgetter
def I(): return int(input())
def MI(): return map(int, input().split())
def LI(): return list(map(int, input().split()))
def LI2(): return [int(input()) for i in range(n)]
def MXI(): return [[LI()]for i in range(n)]
def SI(): return input().rstrip()
def printns(x): print('\n'.join(x))
def printni(x): print('\n'.join(list(map(str,x))))
inf = 10**17
mod = 10**9 + 7

h,w=MI()
lis=[list(SI()) for i in range(h)]
al=[[-1]*w for i in range(h)]
dp=[[inf]*w for i in range(h)]
'''for i in range(h):
    for j in range(w):
        if lis[i][j]=="#":
            dp[i][j]=-1'''
dp[0][0]= 0 if lis[0][0]=="." else 1
q=deque([[0,0]])
step=[[0,1],[1,0]]
#print(lis)
while q:
    x,y=q.popleft()
    if lis[x][y]==".":
        state=1
    else:
        state=-1
    for i,j in step:
        if x+i>h-1 or y+j>w-1:
            continue
        elif state==1:
            if al[x+i][y+j]<0:
                al[x+i][y+j]=0
                q.append([x+i,y+j])
            if lis[x+i][y+j]=="#":
                dp[x+i][y+j]=min(dp[x+i][y+j],dp[x][y]+1)
            else:
                dp[x+i][y+j]=min(dp[x+i][y+j],dp[x][y])
        elif state==-1:
            if al[x+i][y+j]<0:
                al[x+i][y+j]=0
                q.append([x+i,y+j])
            dp[x+i][y+j]=min(dp[x+i][y+j],dp[x][y])
print(dp[-1][-1])

Submission status: Accepted

Solution code:
H, W = list(map(int, input().split()))
m = [list(input()) for _ in range(H)]
scores = [[None for _ in range(W)] for _ in range(H)]
def calc(i, j):
#     print(f'{i}, {j}')
    global m, scores, H, W
    if scores[i][j] is not None:
        return scores[i][j]
    if i == H - 1 and j == W - 1 and i != 0 and j != 0:
        score = 0
        scores[i][j] = score
#         print(f'i: {i}, j: {j}, score: {score}')
        return score
    diff = []
    if j < W - 1:
        diff.append((0, 1))
    if i < H - 1:
        diff.append((1, 0))
#     print(f'diff: {diff}')
    score_cand = []
    for di, dj in diff:
        additional = 0
        if (m[i][j] == '.' and m[i+di][j+dj] == '#') or (i == 0 and j == 0 and m[0][0] == '#'):
            additional += 1 
        score = calc(i+di, j+dj) + additional
        score_cand.append(score)
    score = min(score_cand)
    scores[i][j] = score
#     print(f'i: {i}, j: {j}, score: {score}')
    return score
print(calc(0, 0))

Submission status: Accepted

Solution code:
h,w = list(map(int, input().split()))
board = []
dp = []
INF=10**18
for _ in range(h):
    board.append(input())
    dp.append([INF]*w)

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

dp[0][0]=1 if board[0][0] == '#' else 0
for y in range(h):
    for x in range(w):
        dp_list=[dp[y][x]]
        if x>0:
            dp_left = dp[y][x-1]
            if board[y][x-1] != board[y][x] and board[y][x] == '#':
                dp_left += 1
            dp_list.append(dp_left)
        if y>0:
            dp_up=dp[y-1][x]
            if board[y-1][x] != board[y][x] and board[y][x] == '#':
                dp_up += 1
            dp_list.append(dp_up)
        dp[y][x]=min(dp_list)

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

Submission status: Accepted

Solution code:
_,*s=open(0);t='.';b=t*101;q=range(101)
for i,s in enumerate(s):
 a=[i]
 for x,y,z,c in zip(b,t+s,s,q):a+=min(c+(x==t>z),a[-1]+(y==t>z)),
 b,q=s,a[1:]
print(a[-2])

Submission status: Accepted

Solution code:
H,W=map(int,input().split())
S=[input() for _ in range(H)]
dp=[[10**9]*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):
        for di,dj in [(0,1),(1,0)]:
            ni=i+di
            nj=j+dj
            if ni<H and nj<W:
                if S[i][j]=='.' and S[ni][nj]=='#':
                    dp[ni][nj]=min(dp[ni][nj],dp[i][j]+1)
                else:
                    dp[ni][nj]=min(dp[ni][nj],dp[i][j])
print(dp[-1][-1])

Submission status: Accepted

Solution code:
H,W=map(int,input().split())
S=tuple(tuple(input()) for _ in range(H))

dp=[[10**9 for _ in range(W)] for __ in range(H)]
dp[0][0]=int(S[0][0]!='.')
for i in range(H):
    for j in range(W):
        for di,dj in [[0,1],[1,0]]:
            ni=i+di
            nj=j+dj
            if 0<=ni<H and 0<=nj<W:
                WB=S[i][j]=='.' and S[ni][nj]=='#'
                dp[ni][nj]=min(dp[ni][nj],dp[i][j]+int(WB))
print(dp[-1][-1])

Submission status: Accepted

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

# ある経路をきめる.
# そのとき(白マスから黒マスに移動する回数)＝(その経路がいい経路にするための操作回数）
dp = [[float("inf")]*w for _ in range(h)]
if s[0][0] == "#":
    dp[0][0] = 1
else:
    dp[0][0] = 0
# dp[i][j]は00からijに行くときに白マスから黒マスに移動する回数の最小値
for i in range(h):
    for j in range(w):
        if i+1 < h:
            if s[i][j] == "." and s[i+1][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:
            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+1], dp[i][j])
print(dp[h-1][w-1])

Submission status: Accepted

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

# ある経路をきめる.
# そのとき(白マスから黒マスに移動する回数)＝(その経路がいい経路にするための操作回数）
dp = [[float("inf")]*w for _ in range(h)]
if s[0][0] == "#":
    dp[0][0] = 1
else:
    dp[0][0] = 0
# dp[i][j]は00からijに行くときに白マスから黒マスに移動する回数の最小値
for i in range(h):
    for j in range(w):
        if i+1 < h:
            count1 = dp[i][j]
            if s[i][j] == "." and s[i+1][j] == "#":
                count1 += 1
            dp[i+1][j] = min(dp[i+1][j], count1)
        if j+1 < w:
            count2 = dp[i][j]
            if s[i][j] == "." and s[i][j+1] == "#":
                count2 += 1
            dp[i][j+1] = min(dp[i][j+1], count2)
print(dp[h-1][w-1])

Submission status: Accepted

Solution code:
import sys

sys.setrecursionlimit(10 ** 6)
input = sys.stdin.readline
from math import floor, sqrt, factorial, hypot, log  # log2ないｙｐ
from heapq import heappop, heappush, heappushpop
from collections import Counter, defaultdict, deque
from itertools import accumulate, permutations, combinations, product, combinations_with_replacement
from bisect import bisect_left, bisect_right
from copy import deepcopy
from fractions import gcd
from random import randint


def ceil(a, b): return (a + b - 1) // b


inf = float('inf')
mod = 10 ** 9 + 7


def pprint(*A):
    for a in A:     print(*a, sep='\n')


def INT_(n): return int(n) - 1


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


def MF(): return map(float, input().split())


def MI_(): return map(INT_, input().split())


def LI(): return list(MI())


def LI_(): return [int(x) - 1 for x in input().split()]


def LF(): return list(MF())


def LIN(n: int): return [I() for _ in range(n)]


def LLIN(n: int): return [LI() for _ in range(n)]


def LLIN_(n: int): return [LI_() for _ in range(n)]


def LLI(): return [list(map(int, l.split())) for l in input()]


def I(): return int(input())


def F(): return float(input())


def ST(): return input().replace('\n', '')


def main():
    H, W = MI()
    grid = [ST() for _ in range(H)]
    dp = [[inf] * W for _ in range(H)]
    dp[0][0] = int(grid[0][0] == "#")
    for h in range(H):
        for w in range(W):
            if h < H-1:
                if grid[h + 1][w] == grid[h][w] or grid[h+1][w] == ".":
                    dp[h+1][w] = min(dp[h+1][w], dp[h][w])
                else:
                    dp[h+1][w] = min(dp[h+1][w], dp[h][w] + 1)
            if w < W-1:
                if grid[h][w+1] == grid[h][w] or grid[h][w+1] == ".":
                    dp[h][w+1] = min(dp[h][w+1], dp[h][w])
                else:
                    dp[h][w+1] = min(dp[h][w+1], dp[h][w]+1)
    print(dp[H-1][W-1])

if __name__ == '__main__':
    main()

    # H, W = MI()
    # grid = [ST() for _ in range(H)]
    #
    # # DP = [[[inf,inf] for _ in range(W)] for _ in range(H)]
    # # DP[0][0][0] = 0
    # DP = [[inf] * W for _ in range(H)]
    # DP[0][0] = int(grid[0][0] == "#")
    # for h in range(H):
    #     for w in range(W):
    #         if h + 1 < H:
    #             if grid[h][w] == grid[h + 1][w] or grid[h + 1][w] == ".":
    #                 DP[h + 1][w] = min(DP[h + 1][w], DP[h][w])
    #             else:
    #                 DP[h + 1][w] = min(DP[h + 1][w], DP[h][w] + 1)
    #         if w + 1 < W:
    #             if grid[h][w] == grid[h][w + 1] or grid[h][w + 1] == ".":
    #                 DP[h][w + 1] = min(DP[h][w + 1], DP[h][w])
    #             else:
    #                 DP[h][w + 1] = min(DP[h][w + 1], DP[h][w] + 1)
    # print(DP[-1][-1])