Problem:


Score : 400 points

Problem Statement

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

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

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

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

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

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

Constraints

2 \leq H, W \leq 100

Input

Input is given from Standard Input in the following format:

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

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

Output

Print the minimum number of operations needed.

Sample Input 1

3 3
.##
.#.
##.

Sample Output 1

1

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

Sample Input 2

2 2
#.
.#

Sample Output 2

2

Sample Input 3

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

Sample Output 3

0

No operation may be needed.

Sample Input 4

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

Sample Output 4

4



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


Sample output:
1

Submission status: Accepted

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

inf = 10**6
L = [[inf]*W for _ in range(H)]
if S[0][0] == ".":
    L[0][0] = 0
else:
    L[0][0] = 1

for i in range(H):
    for j in range(W):
        n1 = inf
        n2 = inf
        if i > 0:
            if S[i-1][j] == "." and S[i][j] == "#":
                n1 = L[i-1][j] + 1
            else:
                n1 = L[i-1][j]
        if j > 0:
            if S[i][j-1] == "." and S[i][j] == "#":
                n2 = L[i][j-1] + 1
            else:
                n2 = L[i][j-1]
        L[i][j] = min(L[i][j], n1, n2)

print(L[-1][-1])

Submission status: Accepted

Solution code:
from collections import deque
# import math


def bfs(maze, mazeColor, h, w, sy, sx, gy, gx):
    for y in range(h):
        for x in range(w):
            maze[y][x] = float("inf")

    if mazeColor[sy][sx] == '.':
        maze[sy][sx] = 0
    else:
        maze[sy][sx] = 1
    que = deque([[sy, sx]])
    while que:
        y, x = que.popleft()
        for i, j in [(1, 0), (0, 1)]:
            nexty, nextx = y + i, x + j
            distColor = mazeColor[nexty][nextx]
            beforeColor = mazeColor[y][x]
            dist = maze[nexty][nextx]
            if distColor != '#':
                if dist > maze[y][x]:
                    maze[nexty][nextx] = maze[y][x] + 0
                    que.append([nexty, nextx])
            else:
                if dist > maze[y][x]:
                    if beforeColor == '.':
                        maze[nexty][nextx] = maze[y][x] + 1
                    else:
                        maze[nexty][nextx] = maze[y][x] + 0
                    que.append([nexty, nextx])

    # for i in range(len(maze[0])):
    #    print(maze[i])
    print(maze[gy][gx])


h, w = map(int, input().split())
mazeColor = ['#'+'#'*w+'#']
for i in range(h):
    mazeColor.append('#'+input()+'#')
mazeColor.append('#'+'#'*w+'#')

maze = [[0 for j in range(w+2)] for i in range(h+2)]

bfs(maze, mazeColor, h+1, w+1, 1, 1, h, w)

Submission status: Accepted

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

# process
dp = [[100]*(W+1) for _ in range(H+1)]
dp2 = [[True]*(W+1) for _ in range(H+1)]
dp[0][1] = 0
for i in range(H):
    for j in range(W):
        if S[i][j] == '#':
            x = dp[i][j+1]+1 if dp2[i][j+1] else dp[i][j+1]
            y = dp[i+1][j]+1 if dp2[i+1][j] else dp[i+1][j]
            dp2[i+1][j+1] = False
        else:
            x = dp[i][j+1]
            y = dp[i+1][j]
            dp2[i+1][j+1] = True
        dp[i+1][j+1] = min(dp[i+1][j+1], x, y)

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

Submission status: Accepted

Solution code:
H,W=map(int,input().split())
lst=[[] for f in range(H)]
ans=[[0 for e in range(W)] for f in range(H)]
for i in range(H):
 lst[i]=[(d) for d in input()]
for i in range(1,H):
 if lst[i][0]!=lst[i-1][0]:
  ans[i][0]=ans[i-1][0]+1
 else:
  ans[i][0]=ans[i-1][0]
for j in range(1,W):
 if lst[0][j]!=lst[0][j-1]:
  ans[0][j]=ans[0][j-1]+1
 else:
  ans[0][j]=ans[0][j-1]
for i in range(1,H):
 for j in range(1,W):
  if lst[i][j]==lst[i][j-1]:
   a=0
  else:
   a=1
  if lst[i][j]==lst[i-1][j]:
   b=0
  else:
   b=1
  ans[i][j]=min(ans[i][j-1]+a,ans[i-1][j]+b)
if lst[0][0]=="."and lst[H-1][W-1]==".":
 print((ans[H-1][W-1])//2)
elif lst[0][0]=="#"and lst[H-1][W-1]=="#":
 print((ans[H-1][W-1]+2)//2)
else:
 print((ans[H-1][W-1]+1)//2)

Submission status: Accepted

Solution code:
H, W = map(int, input().split())
s = [input() for _ in range(H)]
dp = [[0]*W for _ in range(H)]
if s[0][0] == "#": dp[0][0] = 1
for w in range(1, W):
    dp[0][w] += dp[0][w-1]
    if s[0][w] == "#" and s[0][w-1] != "#": dp[0][w] += 1
for h in range(1, H):
    dp[h][0] += dp[h-1][0]
    if s[h][0] == "#" and s[h-1][0] != "#": dp[h][0] += 1
        
for h in range(1, H):
    for w in range(1, W):
        res0 = dp[h-1][w]
        res1 = dp[h][w-1]
        if s[h][w] == "#":
            if s[h-1][w] != "#": res0 += 1
            if s[h][w-1] != "#": res1 += 1
        dp[h][w] += min(res0, res1)
print(dp[H-1][W-1])

Submission status: Accepted

Solution code:
H,W=map(int,input().split())
dp=[[0 for i in range(W)] for k in range(H)]
ALL=[]
for i in range(H):
  S=input()
  ALL+=[S]
  for k in range(W):
    if i==0 and k==0:
      if S[k]=="#":
        dp[i][k]=1
      else:
        dp[i][k]=0
    elif i==0:
      if S[k]=="#" and S[k-1]==".":
        dp[i][k]=dp[i][k-1]+1
      else:
        dp[i][k]=dp[i][k-1]
    elif k==0:
      if S[k]=="#" and ALL[i-1][k]==".":
        dp[i][k]=dp[i-1][k]+1
      else:
        dp[i][k]=dp[i-1][k]
    else:
      if S[k]=="#":
        if S[k-1]=="#" and ALL[i-1][k]=="#":
          dp[i][k]=min(dp[i][k-1],dp[i-1][k])
        elif S[k-1]=="#" and ALL[i-1][k]==".":
          dp[i][k]=min(dp[i][k-1],dp[i-1][k]+1)
        elif S[k-1]=="." and ALL[i-1][k]=="#":
          dp[i][k]=min(dp[i][k-1]+1,dp[i-1][k])
        else:
          dp[i][k]=min(dp[i][k-1],dp[i-1][k])+1
      else:
        dp[i][k]=min(dp[i][k-1],dp[i-1][k])        
ans=dp[H-1][W-1]
print(ans)

Submission status: Accepted

Solution code:
H,W=map(int,input().split())
dp=[[0 for i in range(W)] for k in range(H)]
ALL=[]
for i in range(H):
  S=input()
  ALL+=[S]
  for k in range(W):
    if i==0 and k==0:
      if S[k]=="#":
        dp[i][k]=1
      else:
        dp[i][k]=0
    elif i==0:
      if S[k]=="#" and S[k-1]=="#":
        dp[i][k]=dp[i][k-1]
      elif S[k]=="." and S[k-1]==".":
        dp[i][k]=dp[i][k-1]
      elif S[k]=="." and S[k-1]=="#":
        dp[i][k]=dp[i][k-1]
      else:
        dp[i][k]=dp[i][k-1]+1
    elif k==0:
      if S[k]=="#" and ALL[i-1][k]=="#":
        dp[i][k]=dp[i-1][k]
      elif S[k]=="." and ALL[i-1][k]==".":
        dp[i][k]=dp[i-1][k]
      elif S[k]=="." and ALL[i-1][k]=="#":  
        dp[i][k]=dp[i-1][k]
      else:
        dp[i][k]=dp[i-1][k]+1
    else:
      if S[k]=="#":
        if S[k-1]=="#" and ALL[i-1][k]=="#":
          dp[i][k]=min(dp[i][k-1],dp[i-1][k])
        elif S[k-1]=="#" and ALL[i-1][k]==".":
          dp[i][k]=min(dp[i][k-1],dp[i-1][k]+1)
        elif S[k-1]=="." and ALL[i-1][k]=="#":
          dp[i][k]=min(dp[i][k-1]+1,dp[i-1][k])
        else:
          dp[i][k]=min(dp[i][k-1],dp[i-1][k])+1
      else:
        dp[i][k]=min(dp[i][k-1],dp[i-1][k])        
ans=dp[H-1][W-1]
print(ans)

Submission status: Accepted

Solution code:
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
from itertools import permutations, accumulate, combinations, combinations_with_replacement
from math import sqrt, ceil, floor, factorial
from bisect import bisect_left, bisect_right, insort_left, insort_right
from copy import deepcopy
from operator import itemgetter
from functools import reduce, lru_cache
from fractions import gcd
import sys
def input(): return sys.stdin.readline().rstrip()
def I(): return int(input())
def Is(): return map(int, input().split())
def LI(): return list(map(int, input().split()))
def TI(): return tuple(map(int, input().split()))
def IR(n): return [I() for _ in range(n)]
def LIR(n): return [LI() for _ in range(n)]
def TIR(n): return [TI() for _ in range(n)]
def S(): return input()
def Ss(): return input().split()
def LS(): return list(input())
def SR(n): return [S() for _ in range(n)]
def SsR(n): return [Ss() for _ in range(n)]
def LSR(n): return [LS() for _ in range(n)]
sys.setrecursionlimit(10**6)
MOD = 10**9+7
INF = 10**18
# ----------------------------------------------------------- #

h, w = Is()
s = LSR(h)
y = [1, 0]
x = [0, 1]

@lru_cache(None)
def dfs(sy, sx, gy, gx, ans, flag):
    if sy == gy and sx == gx:
        return 0
    for i in range(2):
        ny = sy + y[i]
        nx = sx + x[i]
        if 0 <= ny < h and 0 <= nx < w:
            if s[ny][nx] == '#':
                if flag:
                    ans = min(ans, dfs(ny, nx, gy, gx, ans, True))
                else:
                    ans = min(ans, dfs(ny, nx, gy, gx, ans, True)+1)
            else:  # s[ny][nx] == '.'
                ans = min(ans, dfs(ny, nx, gy, gx, ans, False))
    return ans

if s[0][0] == '.':
    print(dfs(0, 0, h-1, w-1, INF, False))
else:
    print(dfs(0, 0, h-1, w-1, INF, True)+1)

Submission status: Accepted

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

    dp = [[1 << 60] * W for _ in range(H)]

    dp[0][0] = int(s[0][0] == '#')

    for r in range(H):
        for c in range(W):
            t = dp[r][c]
            if r > 0:
                t = min(t, dp[r - 1][c] + int(s[r - 1][c] == '.' and s[r][c] == '#'))
            if c > 0:
                t = min(t, dp[r][c - 1] + int(s[r][c - 1] == '.' and s[r][c] == '#'))
            dp[r][c] = t

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


if __name__ == '__main__':
    main()

Submission status: Accepted

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

dp = [[h*w for i in range(w+1)] for j in range(h+1)]

dp[0][1] = 0
dp[1][0] = 0

for i in range(h):
    for j in range(w):
        # print("i", i, "j", j, "s[i][j]", s[i][j])
        # print(s[i][j] == '#' and (i == 0 or s[i-1][j] == '.'))
        
        #前の道が（"."またはグリッド外）かつ現在地が#の場合に1を加える
        #前の道が"#"であればまとめて変換できるので何も加えない
        dp[i+1][j+1] = min(
            dp[i][j+1] + (s[i][j] == '#' and (i == 0 or s[i-1][j] == '.')),
            dp[i+1][j] + (s[i][j] == '#' and (j == 0 or s[i][j-1] == '.'))
        )

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

Submission status: Accepted

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

dp = [[h*w for i in range(w+1)] for j in range(h+1)]

dp[0][1] = 0
dp[1][0] = 0

for i in range(h):
    for j in range(w):
        dp[i+1][j+1] = min(
            dp[i][j+1] + (s[i][j] == '#' and (i == 0 or s[i-1][j] == '.')),
            dp[i+1][j] + (s[i][j] == '#' and (j == 0 or s[i][j-1] == '.'))
        )

print(dp[-1][-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)]
    N = H*W
    edge = [[] for _ in range(N)]
    def enc(h,w):
        return h*W+w

    # 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])
if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
from collections import deque


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

INF = 1000
path = [[INF] * W for _ in range(H)]

q = deque()
q.append((0, 0, 0))
path[0][0] = 0
while q:
    s, i, j = q.popleft()
    c = grid[i][j]
    for di, dj in [(1, 0), (0, 1)]:
        ni, nj = i + di, j + dj
        if 0 <= ni < H and 0 <= nj < W:
            nc = grid[ni][nj]
            ns = s + (c != nc)
            if path[ni][nj] > ns:
                path[ni][nj] = ns
                if c == nc:
                    q.appendleft((ns, ni, nj))
                else:
                    q.append((ns, ni, nj))

ans = path[-1][-1]
ans += (grid[0][0] == '#') + (grid[-1][-1] == '#')
print(ans // 2)

Submission status: Accepted

Solution code:
from collections import deque
h, w = map(int, input().split())
s_list = []
for _ in range(h):
    s = input()
    s_list.append(s)
d = deque()
count = 0
if s_list[0][0] == '#':
    count += 1
d.append([0, 0, count])

vis = [[101 for i in range(w)] for j in range(h)]
if s_list[0][0] == '.':
    vis[0][0] = 0
else:
    vis[0][0] = 1
for x in range(h):
    for y in range(w):
        for xx, yy in [[1, 0], [0, 1]]:
            if (0 <= x + xx < h) & (0 <= y + yy < w):
                if (s_list[x][y] == '.') & (s_list[x + xx][y + yy] == '#'):
                    vis[x + xx][y + yy] = min(vis[x][y] + 1, vis[x + xx][y + yy])
                else:
                    vis[x + xx][y + yy] = min(vis[x][y], vis[x + xx][y + yy])          
print(vis[-1][-1])

Submission status: Accepted

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

DP = [[1000]+[0]*W for _ in range(H+1)]
re = [[0]*(W+1) for _ in range(H+1)]
DP[0] = [1000]*(W+1)
DP[0][1] = DP[1][0] = 0

for i in range(1,H+1):
    for j in range(1,W+1):
        if s[i-1][j-1] == ".":
            DP[i][j] = min(DP[i-1][j],DP[i][j-1])
        else:
            u = DP[i-1][j]+1-re[i-1][j]
            l = DP[i][j-1]+1-re[i][j-1]
            DP[i][j] = min(u, l)
            re[i][j] = 1

print(DP[H][W])

Submission status: Accepted

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

def g(j):
    if j==".":
        return 1 #白
    else:
        return 0 #黒
    
S=[]
for j in range(H):
    S.append(list(map(g,input())))


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

for y in range(H):
    if y==0:
        for x in range(W):
            if x==0:
                Z[0][0]=1-S[0][0]
            else:
                Z[y][x]=Z[y][x-1]+(S[y][x-1]==1 and S[y][x]==0)
    else:
        for x in range(W):
            if x==0:
                Z[y][x]=Z[y-1][x]+(S[y-1][x]==1 and S[y][x]==0)
            else:
                Z[y][x]=min(Z[y][x-1]+(S[y][x-1]==1 and S[y][x]==0),Z[y-1][x]+(S[y-1][x]==1 and S[y][x]==0))

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

Submission status: Accepted

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

S = [input() for _ in range(H)]
vis = [[-1 for i in range(W)] for j in range(H)]

for v in range(H):
  for h in range(W):
    if v==0:
      if h==0:
        if S[v][h]=="#":
          vis[v][h]=1
        else:
          vis[v][h]=0
      else:
        if S[v][h-1]=="." and S[v][h]=="#":
          vis[v][h] = vis[v][h-1] + 1
        else:
          vis[v][h] = vis[v][h-1]
    else:
      if h==0:
        if S[v-1][h]=="." and S[v][h]=="#":
          vis[v][h] = vis[v-1][h] + 1
        else:
          vis[v][h] = vis[v-1][h]
      else:
        if S[v-1][h]=="." and S[v][h]=="#":
          bufv = vis[v-1][h] + 1
        else:
          bufv = vis[v-1][h]
        if S[v][h-1]=="." and S[v][h]=="#":
          bufh = vis[v][h-1] + 1
        else:
          bufh = vis[v][h-1]
        vis[v][h] = min(bufv, bufh)
    
    #print(vis)
        
print(vis[H-1][W-1])

Submission status: Accepted

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

S = [input() for _ in range(H)]
vis = [[-1 for i in range(W)] for j in range(H)]

que = [(0,0)]
itr = 0
color = "."
if S[0][0]=="#":
  itr=1
  color="#"
vis[0][0]=itr
while len(que)>0:
  v, h = que.pop(0)
  itr = vis[v][h]
  if itr%2==0:
    color="."
  else:
    color="#"
  que2 = []
  if v+1 < H:
    if S[v+1][h]==color and vis[v+1][h]==-1:
      vis[v+1][h] = itr
      que2.append((v+1,h))
    elif vis[v+1][h]==-1:
      vis[v+1][h] = itr +1
      que.append((v+1,h))
  if h+1 < W:
    if S[v][h+1]==color and vis[v][h+1]==-1:
      vis[v][h+1] = itr
      que2.append((v,h+1))
    elif vis[v][h+1]==-1:
      vis[v][h+1] = itr+1
      que.append((v, h+1))
  while len(que2)>0:
    v, h = que2.pop(0)
    if v+1 < H:
      if S[v+1][h]==color and vis[v+1][h]==-1:
        vis[v+1][h] = itr
        que2.append((v+1,h))
      elif vis[v+1][h]==-1:
        vis[v+1][h] = itr +1
        que.append((v+1,h))
    if h+1 < W:
      if S[v][h+1]==color and vis[v][h+1]==-1:
        vis[v][h+1] = itr
        que2.append((v,h+1))
      elif vis[v][h+1]==-1:
        vis[v][h+1] = itr+1
        que.append((v, h+1))
    
if vis[H-1][W-1]%2 == 0:
  print(vis[H-1][W-1]//2)
else:
  print((vis[H-1][W-1]+1)//2)

Submission status: Accepted

Solution code:
def agc043_a():
    ''' 解説放送見てやってみた '''
    H, W = map(int, input().split())
    grid = []
    grid.append(['#'] * (W+2))  # 周辺埋め
    for _ in range(H):
        grid.append(['#'] + [c for c in str(input())] + ['#'])
    grid.append(['#'] * (W+2))
    grid[1][0] = grid[H][W+1] = '.'  # グリッド外側に白を置く, (1,1)(H,W)が黒の場合に反転カウントするため

    # 白黒が反転する回数を数える
    cost = [[10**6] * (W+2) for _ in range(H+2)]
    cost[1][0] = 0

    for i in range(1, H+1):
        for j in range(1, W+2):
            if i != H and j == W+1: continue  # ゴールの外側のときだけ通過
            rt = cost[i][j-1]
            if grid[i][j-1] != grid[i][j]: rt += 1
            dw = cost[i-1][j]
            if grid[i-1][j] != grid[i][j]: dw += 1
            cost[i][j] = min(rt, dw)

    ans = cost[H][W+1] // 2  # 区間の始まりと終わりを両方カウントしているので半分にする
    print(ans)

agc043_a()

Submission status: Accepted

Solution code:
H, W = map(int, input().split())
dp = [[H*W for __ in range(W)] for _ in range(H)]
dh = [1, 0]
dw = [0, 1]
S = []
for i in range(H):
    s = input()
    S.append(s)

if (S[0][0] == '#'):
    dp[0][0] = 1
else:
    dp[0][0] = 0


for i in range(H):
    for j in range(W):
        for k in range(2):
            nh = i + dh[k]
            nw = j + dw[k]
            if nh >= H or nw >= W:
                continue
            add = 0
            if (S[nh][nw] == "#" and S[i][j] == "."):
                add = 1
            dp[nh][nw] = min(dp[nh][nw], dp[i][j] + add)


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

Submission status: Accepted

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

dp = [[0] * w for i in range(h)]
    
for i in range(h):
    for j in range(w):
        if i == j == 0:
            if maze[i][j] == "#":
                dp[i][j] += 1
                
        if i == 0 and j != 0:
            if maze[0][j] != maze[0][j - 1]:
                dp[0][j] = dp[0][j - 1] + 1
            else:
                dp[0][j] = dp[0][j - 1]
        
        if j == 0 and i != 0:
            if maze[i][0] != maze[i - 1][0]:
                dp[i][0] = dp[i - 1][0] + 1
            else:
                dp[i][0] = dp[i - 1][0]
        
        if i != 0 and j != 0:
            dp[i][j] = min(dp[i - 1][j] + (1 if maze[i][j] != maze[i - 1][j] else 0), dp[i][j - 1] + (1 if maze[i][j] != maze[i][j - 1] else 0))
        
        if i == h - 1 and j == w - 1:
            if maze[i][j] == "#":
                dp[i][j] += 1
                
ans = dp[h - 1][w - 1] // 2

print(ans)

Submission status: Accepted

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

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

if maze[0][0] == "#":
    dp[0][0] = 1
    
for i in range(h):
    for j in range(w):
        if i == j == 0:
            continue
                
        if i == 0:
            if maze[0][j] != maze[0][j - 1]:
                dp[0][j] = dp[0][j - 1] + 1
            else:
                dp[0][j] = dp[0][j - 1]
        
        if j == 0:
            if maze[i][0] != maze[i - 1][0]:
                dp[i][0] = dp[i - 1][0] + 1
            else:
                dp[i][0] = dp[i - 1][0]
        
        if i != 0 and j != 0:
            tmp1 = 0
            tmp2 = 0
            if maze[i][j] != maze[i - 1][j]:
                tmp1 = 1
            if maze[i][j] != maze[i][j - 1]:
                tmp2 = 1
        
            dp[i][j] = min(dp[i - 1][j] + tmp1, dp[i][j - 1] + tmp2)

if maze[h - 1][w - 1] == "#":
    dp[h - 1][w - 1] += 1

ans = dp[h - 1][w - 1] // 2

print(ans)

Submission status: Accepted

Solution code:
from copy import deepcopy
from collections import deque

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

table = [[None] * W for _ in range(H)]
table[0][0] = (0 if S[0][0] == '.' else 1)

D = deque([(0, 0)])
new_D = deque()
while D:
    h, w = D.popleft()
    for dh, dw in ((1, 0), (0, 1)):
        if 0 <= h + dh < H and 0 <= w + dw < W and table[h + dh][w + dw] is None:
            if S[h + dh][w + dw] == S[h][w]:
                D.append((h + dh, w + dw))
                table[h + dh][w + dw] = table[h][w]
            else:
                new_D.append((h + dh, w + dw))
                table[h + dh][w + dw] = table[h][w] + 1
    if not D:
        D = deepcopy(new_D)
        new_D.clear()

print((table[H - 1][W - 1] + 1) // 2)

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
import sys
# from collections import defaultdict, deque
# from math import sqrt, gcd, factorial, tan, pi, sin, cos
def input(): return sys.stdin.readline()[:-1] # warning not \n
# def input(): return sys.stdin.buffer.readline()[:-1]


def solve():
    n, m = [int(x) for x in input().split()]
    dp = [[float('inf') for _ in range(m)] for _ in range(n)]
    s = []
    for i in range(n):
        s.append(input())
        
    for i in range(n):
        for j in range(m):
            c = int(s[i][j] != '.')
            if i == 0 and j == 0:
                dp[i][j] = c
            if i:
                dp[i][j] = min(dp[i][j], dp[i-1][j] + c * (s[i-1][j] != s[i][j]))
            if j:
                dp[i][j] = min(dp[i][j], dp[i][j-1] + c * (s[i][j-1] != s[i][j]))
    # for r in dp:
    #     print(*r)
    print(dp[n-1][m-1])
        




t = 1
# t = int(input())
for case in range(1,t+1):
    ans = solve()



"""
1 -> (1, 2) -> (2 ** 3, 3) -> (3, 1)

"""

Submission status: Accepted

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

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

xn[0][0]=0

for i in range(H+W-1):
  for j in range(i+1):
    if i-j>=W:
      continue
    if j>=H:
      break
    
    w=1
    h=1
    if i-j>=W-1:
      w=0
    if j>=H-1:
      h=0
    if w==1:
      if x[j][i-j]==".":
        if x[j][i-j+1]=="#":
          xn[j][i-j+1]=min(xn[j][i-j]+1,xn[j][i-j+1])
        else:
          xn[j][i-j+1]=min(xn[j][i-j],xn[j][i-j+1])
      else:
        xn[j][i-j+1]=min(xn[j][i-j],xn[j][i-j+1])
    if h==1:
      if x[j][i-j]==".":
        if x[j+1][i-j]=="#":
          xn[j+1][i-j]=min(xn[j][i-j]+1,xn[j+1][i-j])
        else:
          xn[j+1][i-j]=min(xn[j][i-j],xn[j+1][i-j])
      else:
        xn[j+1][i-j]=min(xn[j][i-j],xn[j+1][i-j])

if x[0][0]=="#":
  xn[H-1][W-1]+=1
print(xn[H-1][W-1])

Submission status: Accepted

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

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

dp = [[1000]*W for _ in range(H)]

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

for j in range(W):
    for i in range(H):
        if i <= H - 2:

            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 <= W - 2:

            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=[input() for _ in range(H)]
ans=float("inf")

counter=[[999]*W for _ in range(H)]

def search(i,j,count):
    global ans

    if counter[i][j]!=999:
        ans=min(ans,count+counter[i][j])
        return(counter[i][j])

    dist=999

    if i==H-1 and j==W-1:
        ans=min(ans,count)
        return 0
    countj=count
    counti=count
    
    if j<W-1:
        if S[i][j]=="." and S[i][j+1]=="#":
            countj+=1
        dist=search(i,j+1,countj) + (S[i][j]=="." and S[i][j+1]=="#")
    if i<H-1:
        if S[i][j]=="." and S[i+1][j]=="#":
            counti+=1
        dist=min(dist,search(i+1,j,counti)+(S[i][j]=="." and S[i+1][j]=="#"))
    
    counter[i][j]=dist
    return dist
search(0,0,(S[0][0]=="#")*1)
print(ans)

Submission status: Accepted

Solution code:
import queue

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

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

ini = 0
if s[0][0] == '#':
    ini = 1

dist = [[ini for _ in range(W)] for _ in range(H)]
start = (0,0)

qq = queue.Queue()

for i in range(H):
    for j in range(W):
        tgt = []
        if j == 0:
            pass
        else:
            if s[i][j-1] == '.' and s[i][j] == '#':
                tgt.append(dist[i][j-1] + 1)

            else:
                tgt.append(dist[i][j-1])

        if i == 0:
            pass
        else:
            if s[i-1][j] == '.' and s[i][j] == "#":
                tgt.append(dist[i-1][j] + 1)
            else:
                tgt.append(dist[i-1][j])
        if i + j == 0:
            continue
        dist[i][j] = min(tgt)

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

Submission status: Accepted

Solution code:
H, W = map(int, input().split())
S = [[i for i in input()] for j in range(H)]
dp = [[0 for i in range(W)] for j in range(H)]
if S[0][0] == "#":
    dp[0][0] = 1

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

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

for h in range(1, H):
    for w in range(1, W):

        if S[h][w] == "#":
            if S[h-1][w] == ".":
                c1 = dp[h-1][w] + 1
            else:
                c1 = dp[h-1][w]

            if S[h][w-1] == ".":
                c2 = dp[h][w-1] + 1
            else:
                c2 = dp[h][w-1]

            dp[h][w] = min(c1, c2)

        else:
            dp[h][w] = min(dp[h-1][w], dp[h][w-1])

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

Submission status: Accepted

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

dp=[[1000 for i in range(W+1)] for j in range(H+1)]
dp[0][1] = 0
dp[1][0] = 0

for h in range(H):
    for w in range(W):
        dp[h+1][w+1] = min(
            dp[h][w+1] + (table[h][w]=='#' and (h==0 or table[h-1][w]=='.')),
            dp[h+1][w] + (table[h][w]=='#' and (w==0 or table[h][w-1]=='.'))
        )

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

Submission status: Accepted

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


def main() -> None:
    H, W = rmi()
    s = []
    for h in range(H):
        line = list(map(lambda c: c == '.', list(r())))
        s.append(line)
    dp = []
    for _ in range(H):
        dp.append([H + W + 1] * W)
    dp[0][0] = 0 if s[0][0] else 1
    for h in range(1, H):
        dp[h][0] = dp[h - 1][0] + int(s[h - 1][0] != s[h][0] and not s[h][0])
    for w in range(1, W):
        dp[0][w] = dp[0][w - 1] + int(s[0][w - 1] != s[0][w] and not s[0][w])
    for h in range(1, H):
        for w in range(1, W):
            dp[h][w] = min(dp[h - 1][w] + int(s[h - 1][w] != s[h][w] and not s[h][w]),
                           dp[h][w - 1] + int(s[h][w - 1] != s[h][w] and not s[h][w]))
    print(dp[H - 1][W - 1])


def r() -> str:
    return input().strip()


def ri() -> int:
    return int(r())


def rmi(delim: str = ' ') -> tuple:
    return tuple(map(int, input().split(delim)))


def w(data) -> None:
    print(data)


def wm(*data, delim: str = ' ') -> None:
    print(delim.join(map(str, data)))


if __name__ == '__main__':
    import sys
    sys.setrecursionlimit(10 ** 9)
    main()

Submission status: Accepted

Solution code:

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

def isvalid(r,c):
    return 0 <= r < h and 0 <= c < w

g = [input() for _ in range(h)]
d = [1,0]
queue = [(0,0)]
dist = [[1000000]* w for _ in range(h)]
dist[0][0] = 0
if g[0][0] == '#':
    dist[0][0] = 1
while len(queue) > 0:
    next_queue = []
    for r,c in queue:
        for i in range(2):
            cos = dist[r][c]
            nr = r + d[i]
            nc = c + d[1^i]
            if not isvalid(nr,nc):
                continue
            if  g[r][c] != g[nr][nc]:
                cos += 1
            if cos < dist[nr][nc]:
                dist[nr][nc] = cos
                next_queue.append((nr,nc))
    queue = next_queue
print((dist[h-1][w-1] + 1)//2)

Submission status: Accepted

Solution code:
h, w = map(int, input().split())
s = [list(input()) for _ in range(h)]
dp = [[0] * w for _ in range(h)]
if s[0][0] == "#":
    dp[0][0] = 1
for i in range(h):
    for j in range(w):
        if i == j == 0:
            continue
        elif i == 0:
            dp[i][j] = dp[i][j - 1]
            if not s[i][j] == s[i][j - 1]:
                dp[i][j] += 1
        elif j == 0:
            dp[i][j] = dp[i - 1][j]
            if not s[i][j] == s[i - 1][j]:
                dp[i][j] += 1
        else:
            a, b = dp[i][j - 1], dp[i - 1][j]
            if not s[i][j] == s[i][j - 1]:
                a += 1
            if not s[i][j] == s[i - 1][j]:
                b += 1
            dp[i][j] = min(a, b)
print((dp[h - 1][w - 1] - dp[0][0] + [s[0][0], s[h - 1][w - 1]].count("#")) // 2)