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:
taka,yoko=map(int,input().split())

gen=[]
saisho=[]
for i in range(taka):
    s=input()
    temp=[0]*yoko
    for j in range(yoko):
        if(s[j]=="."):
            temp[j]=1
        else:
            temp[j]=-1
    gen.append(temp)
    saisho.append([-1000]*yoko)


if(gen[0][0]==1):
    saisho[0][0]=0
else:
    saisho[0][0]=1


for i in range(1,yoko):
    if(gen[0][i]==1):
        saisho[0][i]=saisho[0][i-1]
    else:
        if(gen[0][i-1]==-1):
            saisho[0][i]=saisho[0][i-1]
        else:
            saisho[0][i]=saisho[0][i-1]+1

for i in range(1,taka):
    if(gen[i][0]==1):
        saisho[i][0]=saisho[i-1][0]
    else:
        if(gen[i-1][0]==-1):
            saisho[i][0]=saisho[i-1][0]
        else:
            saisho[i][0]=saisho[i-1][0]+1


for i in range(1,taka):
    for j in range(1,yoko):
        if(gen[i][j]==1):
            saisho[i][j]=min(saisho[i][j-1],saisho[i-1][j])
        else:
            ue=saisho[i-1][j]
            hidari=saisho[i][j-1]
            if(gen[i-1][j]==1):
                ue+=1
            if(gen[i][j-1]==1):
                hidari+=1
            saisho[i][j]=min(ue,hidari)

print(saisho[taka-1][yoko-1])

Submission status: Accepted

Solution code:
def ans_dp(H,W,M):
    dp = [[0 for i in range(W)] for j in range(H)]
    flag = [[0 for i in range(W)] for j in range(H)]
    if M[0][0] == "#":
        dp[0][0] = 1
        flag[0][0] = 1
    else:
        dp[0][0] == 0
    for i in range(1,W):
        if M[0][i] == "#":
            flag[0][i] = 1
            if flag[0][i-1] == 1:
                dp[0][i] = dp[0][i-1]
            else:
                dp[0][i] = dp[0][i-1] + 1 
        else:##M[0][i] = "."
            dp[0][i] = dp[0][i-1]
    for j in range(1,H):
        if M[j][0] == "#":
            flag[j][0] = 1
            if flag[j-1][0] == 1:
                dp[j][0] = dp[j-1][0]
            else:
                dp[j][0] = dp[j-1][0] + 1 
        else:##M[0][i] = "."
            dp[j][0] = dp[j-1][0]
    
    for i in range(1,H):
        for j in range(1,W):
            if M[i][j] == "#":
                flag[i][j] = 1
                dp[i][j] = min(dp[i-1][j]+int(not flag[i-1][j]),dp[i][j-1]+int(not flag[i][j-1]))
            else:#M[i][j] == "."
                dp[i][j] = min(dp[i-1][j],dp[i][j-1])
    return dp[-1][-1]

def main():
    H,W = map(int,input().split())
    M = []
    for i in range(H):
        M.append(list(input()))
    print(ans_dp(H,W,M))
 
if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
H,W=map(int,input().split())
L=[]
l=["*" for i in range(W+2)]
L.append(l)
for i in range(H):
    s=["*"]+list(input())+["*"]
    L.append(s)
L.append(l)
#print(L)

X=[1,0,-1,0]
Y=[0,1,0,-1]

cnt=0
if L[1][1]=="#":
    cnt+=1

C=[[10000 for i in range(W+2)]for j in range(H+2)]
Q=[(0,1,1)]
#print(L)
import heapq
heapq.heapify(Q)
for i in range(10**6):
    if len(Q)==0:
        break
    d,h,w=Q[0]
    heapq.heappop(Q)
    if C[h][w]==10000:
        C[h][w]=d
        for j in range(2):
            if C[h+X[j]][w+Y[j]]==10000 and L[h+X[j]][w+Y[j]]!="*":
                if L[h+X[j]][w+Y[j]]=="#" and L[h][w]==".":
                    heapq.heappush(Q,(d+1,h+X[j],w+Y[j]))
                else:
                    heapq.heappush(Q,(d,h+X[j],w+Y[j]))
print(C[H][W]+cnt)

Submission status: Accepted

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

is_white = True
st = []
st.append([False, H-1, W-1, 0])
dp = [[1000] * W for i in range(H)]

for h in reversed(range(H)):
    for w in reversed(range(W)):
        if h == H-1 and w == W-1:
            if s[h][w] == '#':
                dp[h][w] = 1
            else:
                dp[h][w] = 0
            continue

        if w+1 < W:
            cnt = dp[h][w+1]
            if s[h][w] == '#' and s[h][w+1] == '.':
                cnt += 1
            if cnt < dp[h][w]:
                dp[h][w] = cnt

        if h+1 < H:
            cnt = dp[h+1][w]
            if s[h][w] == '#' and s[h+1][w] == '.':
                cnt += 1
            if cnt < dp[h][w]:
                dp[h][w] = cnt

print(dp[0][0])

Submission status: Accepted

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

import numpy as np
dp = np.zeros((h,w),np.int32)
s = np.full((h,w),'.',np.str)
for H in range(h):
    S = input()
    for W in range(w):
        s[H][W] = S[W]
        own = s[H][W]
        if H==0 and W==0: dp[H][W] = 0 if own=='.' else 1
        elif H==0: dp[H][W] = dp[H][W-1]+1 if s[H][W-1]=='.' and own=='#' else dp[H][W-1]
        elif W==0: dp[H][W] = dp[H-1][W]+1 if s[H-1][W]=='.' and own=='#' else dp[H-1][W]
        else:
            dp[H][W] = min(dp[H][W-1], dp[H-1][W])
            if own=='#':
                if s[H][W-1]=='.' and s[H-1][W]=='.': dp[H][W] += 1
                elif s[H][W-1]=='#' and s[H-1][W]=='.': dp[H][W] = min(dp[H][W-1], dp[H-1][W]+1)
                elif s[H][W-1]=='.' and s[H-1][W]=='#': dp[H][W] = min(dp[H][W-1]+1, dp[H-1][W])
print(dp[h-1,w-1])

Submission status: Accepted

Solution code:
H,W = [int(i.strip()) for i in input().split(' ')]

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

F = [[0] * 10] * 10

arrive = {}
if MAP[0][0] == '#':
    arrive[(0,0)] = 1
else:
    arrive[(0,0)] = 0

while True:
    A = {}
    for p , v in arrive.items():
        if p[0]+1 < H:
            if MAP[p[0]+1][p[1]] == '.':
                if not (p[0]+1 , p[1]) in A:
                    A[(p[0]+1 , p[1])] = v 
                else:
                    t = A[(p[0]+1 , p[1])]
                    A[(p[0]+1 , p[1])] = v if v < t else t
            else:
                if MAP[p[0]][p[1]] == '#':
                    v2 = v
                else:
                    v2 = v + 1
                if not (p[0]+1 , p[1]) in A:
                    A[(p[0]+1, p[1])] = v2
                else:
                    t = A[(p[0]+1 , p[1])]
                    A[(p[0]+1 , p[1])] = v2 if v2 < t else t

        if p[1] + 1 < W:
            if MAP[p[0]][p[1] + 1] == '.':
                if not ( p[0] , p[1] + 1) in A:
                    A[( p[0] , p[1] + 1)] = v 
                else:
                    t = A[( p[0] , p[1] + 1)]
                    A[( p[0] , p[1] + 1)] = v if v < t else t
            else:
                if MAP[p[0]][p[1]] == '#':
                    v2 = v
                else:
                    v2 = v + 1
                if not ( p[0] , p[1] + 1) in A:
                    A[( p[0] , p[1] + 1)] = v2
                else:
                    t = A[( p[0] , p[1] + 1)]
                    A[( p[0] , p[1] + 1)] = v2 if v2 < t else t

    if (H-1,W-1) in A:
        print(A[(H-1,W-1)])
        exit()

    else:
        arrive = A.copy()

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
H, W = map(int, input().split())
s = [0 for i in range(H)]
for i in range(H):
    s[i] = str(input())

l = [[0 for i in range(W)] for j in range(H)]

for i in range(H):
    for j in range(W):
        if s[i][j] == '#':
            l[i][j] = 1

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

dp[0][0] = l[0][0]

for i in range(1, W):
    dp[0][i]  = dp[0][i-1]
    if l[0][i] != l[0][i-1]:
        dp[0][i] += 1
for i in range(1, H):
    dp[i][0] = dp[i-1][0]
    if l[i][0] != l[i-1][0]:
        dp[i][0] += 1

for i in range(1, H):
    for j in range(1, W):
        a, b = dp[i-1][j], dp[i][j-1]
        if l[i-1][j] != l[i][j]:
            a += 1
        if l[i][j-1] != l[i][j]:
            b += 1
        dp[i][j] = min(a, b)
if l[0][0] == l[H-1][W-1] == 0:
    print(dp[H-1][W-1] // 2)

else:
    print(max(1, (dp[H-1][W-1] + 1)//2))

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(100000)

H, W = map(int, input().split())
S = [input() for _ in range(H)]
cost = [[0]*W for _ in range(H)]
cost[0][0] = 1 if S[0][0] == '#' else 0
for w in range(1,W):
  if S[0][w-1] == '.' and S[0][w] == '#':
    cost[0][w] = cost[0][w-1] + 1
  else:
    cost[0][w] = cost[0][w-1]
for h in range(1,H):
  if S[h-1][0] == '.' and S[h][0] == '#':
    cost[h][0] = cost[h-1][0] + 1
  else:
    cost[h][0] = cost[h-1][0]

for h in range(1,H):
  for w in range(1,W):
    if S[h-1][w] == '.' and S[h][w] == '#':
      ch = cost[h-1][w] + 1
    else:
      ch = cost[h-1][w]
    if S[h][w-1] == '.' and S[h][w] == '#':
      cw = cost[h][w-1] + 1
    else:
      cw = cost[h][w-1]
    cost[h][w] = min(ch, cw)

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

Submission status: Accepted

Solution code:
from heapq import heappush, heappop
INF = 10**10


def dijkstra(G, H, W):
    dist = [INF] * (10 ** 4)
    que = [(0, 0)]
    dist[0] = 0
    while que:
        c, v = heappop(que)
        if dist[v] < c:
            continue
        for t, cost in G[v]:
            if dist[v] + cost < dist[t]:
                dist[t] = dist[v] + cost
                heappush(que, (dist[t], t))
    return dist[(H-1)*100+W-1]


def Gragh(H, W, S):
    G = [[] for _ in range(10**4)]
    for i in range(H-1):
        for j in range(W-1):
            if S[i][j] == "." and S[i+1][j] == "#":
                G[100 * i + j].append((100 * (i + 1) + j, 1))
            else:
                G[100 * i + j].append((100 * (i + 1) + j, 0))

            if S[i][j] == "." and S[i][j+1] == "#":
                G[100 * i + j].append((100 * i + j + 1, 1))
            else:
                G[100 * i + j].append((100 * i + j + 1, 0))

        for i in range(H - 1):
            if S[i][-1] == "." and S[i+1][-1] == "#":
                G[100*i+W-1].append((100*(i+1)+W-1, 1))
            else:
                G[100 * i + W-1].append((100 * (i + 1) + W-1, 0))

        for j in range(W-1):
            if S[-1][j] == "." and S[-1][j + 1] == "#":
                G[100 * (H-1) + j].append((100 * (H-1) + j + 1, 1))
            else:
                G[100 * (H-1) + j].append((100 * (H-1) + j + 1, 0))
    return G


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

G = Gragh(H, W, S)

if S[0][0] == "#":
    ans = dijkstra(G, H, W) + 1
    print(ans)
else:
    ans = dijkstra(G, H, W)
    print(ans)

Submission status: Accepted

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

S = [input() for _ in range(H)]
X = [[[int(1e9), 0] for i in range(W)] for j in range(H)]
p = [[0, 0]]
if S[0][0] == '#':
  X[0][0][0], X[0][0][1] = 1, 1
else:
  X[0][0][0], X[0][0][1] = 0, 0
for i in range(H):
  for j in range(W):
    if S[i][j] == '#':
      X[i][j][1] = 1
for m in range(H+W-2):
  n = len(p)
  for i in range(n):
    x = p[i][:]
    if x[0] < H - 1:
      p.append([x[0]+1, x[1]])
    if x[0] == 0 and x[1] < W - 1:
      p.append([x[0], x[1]+1])
  p = p[n:]
  n = len(p)
  for i in range(n):
    x = p[i][:]
    if x[0] > 0 and x[1] > 0:
      X[x[0]][x[1]][0] = min(X[x[0]-1][x[1]][0] + (1-X[x[0]-1][x[1]][1])*X[x[0]][x[1]][1], X[x[0]][x[1]-1][0] + (1-X[x[0]][x[1]-1][1])*X[x[0]][x[1]][1])
    elif x[0] == 0 and x[1] > 0:
      X[x[0]][x[1]][0] = X[x[0]][x[1]-1][0] + (1-X[x[0]][x[1]-1][1])*X[x[0]][x[1]][1]
    elif x[0] > 0 and x[1] == 0:
      X[x[0]][x[1]][0] = X[x[0]-1][x[1]][0] + (1-X[x[0]-1][x[1]][1])*X[x[0]][x[1]][1]
print(X[H-1][W-1][0])

Submission status: Accepted

Solution code:
h, w = map(int, input().split())
map = []
ansList = [[0] * w for i in range(h)]
#print(list(input()))
for x in range(h):
    a = list(input())
    map.append(a)

prev = ""
for y in range(h):
    for x in range(w):
        if y == 0 and x == 0: 
            val = 0
            prev = ""
        elif y == 0 or (x > 0 and ansList[y - 1][x] > ansList[y][x - 1]):
            val = ansList[y][x - 1]
            prev = map[y][x - 1]
        elif x == 0 or (y > 0 and ansList[y - 1][x] < ansList[y][x - 1]):
            val = ansList[y - 1][x]
            prev = map[y - 1][x]
        if x > 0 and y > 0 and ansList[y - 1][x] == ansList[y][x - 1] and (map[y - 1][x] != map[y][x - 1]):
            val = ansList[y - 1][x]
            prev = "#"
        elif x > 0 and y > 0 and ansList[y - 1][x] == ansList[y][x - 1] and (map[y - 1][x] == map[y][x - 1]):
            val = ansList[y - 1][x]
            prev = map[y - 1][x]

        if map[y][x] == "#" and prev != "#": ansList[y][x] = val + 1
        elif map[y][x] == "#" and prev == "#": ansList[y][x] = val
        else: ansList[y][x] = val
print(ansList[h - 1][w - 1])

Submission status: Accepted

Solution code:
def ans_dp(H,W,M):
    dp = [[0 for i in range(W)] for j in range(H)]
    flag = [[0 for i in range(W)] for j in range(H)]
    if M[0][0] == "#":
        dp[0][0] = 1
        flag[0][0] = 1
    else:
        dp[0][0] == 0
    for i in range(1,W):
        if M[0][i] == "#":
            flag[0][i] = 1
            if flag[0][i-1] == 1:
                dp[0][i] = dp[0][i-1]
            else:
                dp[0][i] = dp[0][i-1] + 1 
        else:##M[0][i] = "."
            dp[0][i] = dp[0][i-1]
    for j in range(1,H):
        if M[j][0] == "#":
            flag[j][0] = 1
            if flag[j-1][0] == 1:
                dp[j][0] = dp[j-1][0]
            else:
                dp[j][0] = dp[j-1][0] + 1 
        else:##M[0][i] = "."
            dp[j][0] = dp[j-1][0]
    
    for i in range(1,H):
        for j in range(1,W):
            if M[i][j] == "#":
                flag[i][j] = 1
                dp[i][j] = min(dp[i-1][j]+int(not flag[i-1][j]),dp[i][j-1]+int(not flag[i][j-1]))
            else:#M[i][j] == "."
                dp[i][j] = min(dp[i-1][j],dp[i][j-1])
    """
    for i in range(H):
        print(dp[i])
    for i in range(H):
        print(flag[i])
    """
    return dp[H-1][W-1]

def main():
    H,W = map(int,input().split())
    M = []
    for i in range(H):
        M.append(list(input()))
    print(ans_dp(H,W,M))
 
if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
h, w = map(int, input().split())
INF = 10**5
MAP = ["."*(w+2)]
for _ in range(h):
    MAP.append("."+input()+".")
MAP.append("."*(w+2))
ROUTE = [[0]*(w+2) for _ in range(h+2)]
for i in range(2, w+1):
    ROUTE[0][i] = INF
for i in range(2, h+1):
    ROUTE[i][0] = INF

for i in range(1, h+1):
    for j in range(1, w+1):
        if MAP[i][j] == ".":
            x1 = ROUTE[i][j-1]
            x2 = ROUTE[i-1][j]
        else:
            if MAP[i][j-1] == "#":
                x1 = ROUTE[i][j-1]
            else:
                x1 = ROUTE[i][j-1]+1

            if MAP[i-1][j] == "#":
                x2 = ROUTE[i-1][j]
            else:
                x2 = ROUTE[i-1][j]+1
        ROUTE[i][j] = min(x1, x2)


print(ROUTE[h][w])

Submission status: Accepted

Solution code:
from sys import stdin


def main():
    input = lambda: stdin.readline()[:-1]
    H, W = map(int, input().split())
    S = stdin.read().splitlines()

    grid = [[0] * W for _ in [0] * H]
    if S[0][0] == '#':
        grid[0][0] = 1

    for c in range(1, W):
        if S[0][c] == '#' and S[0][c-1] == '.':
            grid[0][c] = grid[0][c-1] + 1
        else:
            grid[0][c] = grid[0][c-1]

    for r in range(1, H):
        if S[r][0] == '#' and S[r-1][0] == '.':
            grid[r][0] = grid[r-1][0] + 1
        else:
            grid[r][0] = grid[r-1][0]

    for r in range(1, H):
        for c in range(1, W):
            if S[r][c] == '#':
                if S[r-1][c] == '.':
                    a = grid[r-1][c] + 1
                else:
                    a = grid[r-1][c]
                if S[r][c-1] == '.':
                    b = grid[r][c-1] + 1
                else:
                    b = grid[r][c-1]
                grid[r][c] = min(a, b)
            else:
                grid[r][c] = min(grid[r-1][c], grid[r][c-1])
    print(grid[-1][-1])


main()

Submission status: Accepted

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

def next(h, w, pre_h, pre_w):
    if S[pre_h][pre_w] == '.' and S[h][w] == '#':
        return r[pre_h][pre_w] + 1
    else:
        return r[pre_h][pre_w]

r = []

r.append([])
r[0].append( 1 if S[0][0] == '#' else 0)
for w in range(1,W):
    r[0].append( next(0, w, 0, w-1) )

for h in range(1,H):
    r.append([])
    r[h].append( next(h, 0, h-1, 0) )

    for w in range(1, W):
        if r[h-1][w] > r[h][w-1] or \
            (r[h-1][w] == r[h][w-1] and S[h][w-1] == S[h][w]):
            r[h].append( next(h, w, h, w-1) )
        else:
            r[h].append( next(h, w, h-1, w) )

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

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
import sys
#sys.setrecursionlimit(150000)


def solve(H: int, W: int, s: "List[str]"):
    x=y=0
    k=1 if s[y][x]=="#" else 0
    dt=[[999]*W for _ in range(H)]
    dt[y][x]=1 if s[y][x]=="#" else 0
    for y in range(H):
        for x in range(W):
            if y>0:
                dt[y][x]=min(dt[y][x], dt[y-1][x]+(1 if s[y][x]!=s[y-1][x] else 0))
            if x>0:
                dt[y][x]=min(dt[y][x], dt[y][x-1]+(1 if s[y][x]!=s[y][x-1] else 0))
    print((dt[H-1][W-1]+1)//2)
    #print("#",s,dt)
    """
    for i in range(H+W-2):
        if y<H-1 and s[y][x]==s[y+1][x]:
            y+=1
        elif x<W-1 and s[y][x]==s[y][x+1]:
            x+=1
        else:
            print(x,y,k+1)
            k+=1
            if x<W-1:
                x+=1
            else:
                y+=1
    print(k,(k+1)//2)
    """
    return
        
# Generated by 1.1.6 https://github.com/kyuridenamida/atcoder-tools
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 collections
import sys
input = sys.stdin.readline
H, W = map(int, input().split())
M = []
for i in range(H):
  M.append(list(input().strip()))

queue = collections.deque()
if M[0][0] == '#':
  queue.append((0, 0, 1))
else:
  queue.append((0, 0, 0))
visited = {}
while queue:
  i, j, level = queue.popleft()
  if (i,j) in visited:
    if visited[(i,j)] <= level:
      continue
  visited[(i,j)] = level
  for ni, nj in [(i+1, j), (i, j+1)]:
    if not (ni < H and nj < W):
      continue
    if M[ni][nj] != M[i][j] and M[ni][nj] == '#':
      queue.append((ni, nj, level+1))
    else:
      queue.append((ni, nj, level))
print(visited[(H-1,W-1)])

Submission status: Accepted

Solution code:
def main():
    from collections import deque
    h,w = map(int,input().split())
    l = [list(input()) for i in range(h)]

    dp = [[[-1]*(h*w) for i in range(w)] for i in range(h)]
    q = deque([])
    if l[0][0] == ".":
        q.append((0,0,0,"."))
    else:
        q.append((0,0,1,"#"))
    dx = [0,1]
    dy = [1,0]
    while q:
        
        bx,by,num,bef = q.popleft()
        for j in range(2):
            nx = bx+dx[j]
            ny = by+dy[j]
            if nx < h and ny < w:
                if bef == "." and l[nx][ny] == "#":
                    if dp[nx][ny][num+1] == -1:
                    
                        dp[nx][ny][num+1] = 1
                        q.append((nx,ny,num+1,l[nx][ny]))
                elif dp[nx][ny][num] == -1:
                    dp[nx][ny][num] = 1
                    q.append((nx,ny,num,l[nx][ny]))

    print(dp[-1][-1].index(1))
if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import sys
import copy
sys.setrecursionlimit(100000)
h, w = map(int, input().split())
mapping = [0]*h
for i in range(h):
  mapping[i] = input()
ans = [[[-1, -1, -1] for j in range(w)] for i in range(h)]
def dp(i, j):
  if ans[i][j][0] >= 0:
    pass
  else:
    if i == 0 and j == 0:
      if mapping[i][j] == ".":
        ans[i][j] = [0, 0, 0]
      else:
        ans[i][j] = [1, 0, 0]
    elif i == 0:
      if mapping[i][j] == ".":
        ans[i][j] = copy.deepcopy(dp(i, j-1))
        ans[i][j][1], ans[i][j][2] = i, j
      else:
        ans[i][j] = copy.deepcopy(dp(i, j-1))
        if mapping[i][j-1] == ".":
          ans[i][j][1], ans[i][j][2] = i, j
          ans[i][j][0] += 1
    elif j == 0:
      if mapping[i][j] == ".":
        ans[i][j] = copy.deepcopy(dp(i-1, j))
        ans[i][j][1], ans[i][j][2] = i, j
      else:
        ans[i][j] = copy.deepcopy(dp(i-1, j))
        if mapping[i-1][j] == ".":
          ans[i][j][1], ans[i][j][2] = i, j
          ans[i][j][0] += 1
    else:
      if mapping[i][j] == ".":
        k = min([dp(i-1, j)[0], dp(i, j-1)[0]])
        ans[i][j] = [k, i, j]
      else:
        p = copy.deepcopy(dp(i-1, j))
        if mapping[i-1][j] == ".":
          p[1], p[2] = i, j
          p[0] += 1
        q = copy.deepcopy(dp(i, j-1))
        if mapping[i][j-1] == ".":
          q[1], q[2] = i, j
          q[0] += 1
        if p[0] < q[0]:
          ans[i][j] = copy.deepcopy(p)
        elif p[0] > q[0]:
          ans[i][j] = copy.deepcopy(q)
        elif p[1]+p[2] < q[1]+q[2]:
          ans[i][j] = copy.deepcopy(q)
        else:
          ans[i][j] = copy.deepcopy(p)
  return ans[i][j]

answer = dp(h-1, w-1)
print(answer[0])

Submission status: Accepted

Solution code:
H, W = map(int, input().split())
grids = [input() for _ in range(H)]
dp = [[float('inf') for _ in range(W)] for _ in range(H)]
if grids[0][0] == '#':
    dp[0][0] = 1
else:
    dp[0][0] = 0

for i in range(W):
    for j in range(H):
        if i == 0 and j == 0:
            continue

        if i - 1 < 0:
            val1 = float('inf')
        elif grids[j][i - 1] == '.' and grids[j][i] == '#':
            val1 = dp[j][i - 1] + 1
        else:
            val1 = dp[j][i - 1]

        if j - 1 < 0:
            val2 = float('inf')
        elif grids[j - 1][i] == '.' and grids[j][i] == '#':
            val2 = dp[j - 1][i] + 1
        else:
            val2 = dp[j - 1][i]

        dp[j][i] = min(val1, val2)
        #print(i,j,dp)

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

Submission status: Accepted

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

ans = 0
dp = [[0]*w for i in range(h)]
if masu[0][0] == "#":
    dp[0][0] = 1

for i in range(1,h):
    if masu[i][0] != masu[i-1][0] and masu[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 masu[0][j] != masu[0][j-1] and masu[0][j]=="#":
        dp[0][j] = dp[0][j-1]+1
    else:
        dp[0][j] = dp[0][j-1]


for i in range(1,h):
    for j in range(1,w):
        if masu[i][j] != masu[i-1][j] and masu[i][j]=="#":
            tate = dp[i-1][j]+1
        else:
            tate = dp[i-1][j]

        if masu[i][j] != masu[i][j-1] and masu[i][j]=="#":
            yoko = dp[i][j-1]+1
        else:
            yoko = dp[i][j-1]

        dp[i][j] = min(tate,yoko)


# print(*dp,sep="\n")
print(dp[-1][-1])

Submission status: Accepted

Solution code:
h, w = map(int, input().split())
dat = []
res = []
for i in range(h):
    l = input()
    dat.append(l)
    res.append([99999] * w)
    # None: なし, 0:通路, 1:壁
if dat[0][0] == "#":
    res[0][0] = 1
else:
    res[0][0] = 0

dx = [0, -1]
dy = [-1, 0]

for hh in range(h):
    for ww in range(w):
        for dir in range(len(dx)):
            px = ww + dx[dir]
            py = hh + dy[dir]
            if px >= -1 and py >= -1:
                if dat[py][px] == dat[hh][ww]: # 地形が一緒
                    res[hh][ww] = min(res[hh][ww], res[py][px])
                elif dat[hh][ww] == ".":
                    res[hh][ww] = min(res[hh][ww], res[py][px])
                else:
                    res[hh][ww] = min(res[hh][ww], res[py][px] + 1)
print(res[h-1][w-1])
#print(res)

Submission status: Accepted

Solution code:
from collections import deque
from itertools import product
from sys import stdin
import sys
sys.setrecursionlimit(10 ** 7)
H,W = [int(x) for x in stdin.readline().rstrip().split()]
grid = [input() for _ in range(H)]

# 移動用（上下左右）
mv = [(1, 0),
      (0, 1)]

# スタート位置の設定
for i, j in product(range(H), range(W)):
    if grid[i][j] == 's':
        start = (i, j)

# 訪問したかどうか
is_visited = [[False for _ in range(W)] for _ in range(H)]



def dfs(i, j):
    if not (0 <= i < H) or not (0 <= j < W):
        # 範囲外
        return False
    
    if is_visited[i][j]:
        # 壁または訪問済み
        return False
    
    if grid[i][j] == '#':
        p2.append((i,j))
        return False
 
    is_visited[i][j] = True
    if i == H-1 and j == W-1:
        return True

    for di, dj in mv:
        flg = dfs(i+di, j+dj)
        if flg:
            return True

        
        
def dfs2(i, j):
    if not (0 <= i < H) or not (0 <= j < W):
        # 範囲外
        return False
    
    if is_visited[i][j]:
        # 壁または訪問済み
        return False
    
    if grid[i][j] == '.':
        p1.append((i,j))
        return False
 
    is_visited[i][j] = True
    if i == H-1 and j == W-1:
        return True

    for di, dj in mv:
        flg = dfs2(i+di, j+dj)
        if flg:
            return True
        
ans = 0

p1 = deque([(0,0)])
p2 = deque([])
f = False

while True:
    while p1:
        s1,s2 = p1.popleft()
        if dfs(s1,s2):
            f = True
    if f:
        break
    ans += 1
    while p2:
        s1,s2 = p2.popleft()
        if dfs2(s1,s2):
            f = True
    if f:
        break
print(ans)

Submission status: Accepted

Solution code:
INF = 100000

h, w = map(int, input().split())
S = [list(input()) for i in range(h)]

D = [[INF for i in range(w)] for j in range(h)]

if S[0][0] == '.':
    D[0][0] = 0
else:
    D[0][0] = 1

for i in range(1, h):
    if S[i][0] == '#' and S[i-1][0] == '.':
        D[i][0] = D[i-1][0] + 1
    else:
        D[i][0] = D[i-1][0]

for j in range(1, w):
    if S[0][j] == '#' and S[0][j-1] == '.':
        D[0][j] = D[0][j-1] + 1
    else:
        D[0][j] = D[0][j-1]

for i in range(1, h):
    for j in range(1, w):
        s = S[i][j]
        su = S[i-1][j]
        sl = S[i][j-1]
        if s == '.' or (s == su and s == sl):
            D[i][j] = min(D[i-1][j], D[i][j-1])
        elif s == su:
            D[i][j] = min(D[i-1][j], D[i][j-1]+1)
        elif s == sl:
            D[i][j] = min(D[i-1][j]+1, D[i][j-1])
        else:
            D[i][j] = min(D[i-1][j]+1, D[i][j-1]+1)

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

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(4100000)
from collections import deque

def main():
    H, W = map(int, input().split())
    S = [list(input()) for _ in range(H)]
    visited = [[float('inf')] * W for _ in range(H)]
    if S[0][0] == '#':
        visited[0][0] = 1
    else:
        visited[0][0] = 0
    
    for h in range(H):
        for w in range(W):
            if h + 1 > H - 1 and w + 1 > W - 1:
                continue
            if S[h][w] == '.':
                if h + 1 > H - 1:
                    if S[h][w + 1] == '.':
                        visited[h][w+1] = min(visited[h][w], visited[h][w+1])
                    else:
                        visited[h][w+1] = min(visited[h][w] + 1,visited[h][w+1])
                elif w + 1 > W - 1:
                    if S[h+1][w] == '.':
                        visited[h+1][w] = min(visited[h][w],visited[h+1][w])
                    else:
                        visited[h+1][w] = min(visited[h][w] + 1,visited[h+1][w])
                else:
                    if S[h + 1][w] == '.':
                        visited[h+1][w] = min(visited[h][w],visited[h+1][w])
                    else:
                        visited[h+1][w] = min(visited[h][w] + 1,visited[h+1][w])

                    if S[h][w + 1] == '.':
                        visited[h][w+1] = min(visited[h][w],visited[h][w+1])
                    else:
                        visited[h][w+1] = min(visited[h][w] + 1,visited[h][w+1])

            else:
                if h + 1 > H - 1:
                    visited[h][w+1] = min(visited[h][w],visited[h][w+1])
                elif w + 1 > W - 1:
                    visited[h+1][w] = min(visited[h][w],visited[h+1][w])
                else:
                    visited[h][w+1] = min(visited[h][w],visited[h][w+1])
                    visited[h+1][w] = min(visited[h][w],visited[h+1][w])

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


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
from collections import deque
h, w = map(int, input().split())
c = [list(input()) for _ in range(h)]
moves = ((1, 0), (0, 1))
sy = 0
sx = 0
ty = h-1
tx = w-1

def bfs(sy, sx):
    a,b = 0,0
    dist = [[float('inf')]*w for _ in range(h)]
    dist[0][0] = 0
    if c[0][0] == '#':
        dist[0][0] = 1
    
    for i in range(h-1):
        if c[i+1][0] == "#" and c[i][0] == ".":
            dist[i+1][0] = dist[i][0] + 1
        else:
            dist[i+1][0] = dist[i][0]
            
    for i in range(w-1):
        if c[0][i+1] == "#" and c[0][i] == ".":
            dist[0][i+1] = dist[0][i] + 1
        else:
            dist[0][i+1] = dist[0][i]
            
    for i in range(1,h):
        for j in range(1,w):
            if c[i][j] == "#" and c[i-1][j] == ".":
                a = dist[i-1][j] + 1
            else:
                a = dist[i-1][j]
                
            if c[i][j] == "#" and c[i][j-1] == ".":
                b = dist[i][j-1] + 1
            else:
                b = dist[i][j-1]
                
            dist[i][j] = min(a,b)
 
    return dist 
 
dist = (bfs(0, 0))
print(dist[ty][tx])