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:
import sys
#input = sys.stdin.readline

def main():
    h,w=map(int,input().split())
    s=[list(input()) for _ in range(h)]
    ans=[[0]*w for _ in range(h)]
    if s[0][0]=='#':
        ans[0][0]=1
    for i in range(h):
        for j in range(w):
            if i==0:
                if j==0:
                    continue
                else:
                    if s[i][j]==s[i][j-1]:
                        ans[i][j]=ans[i][j-1]
                    else:
                        ans[i][j]=ans[i][j-1]+1
            else:
                if j==0:
                    if s[i][j]==s[i-1][j]:
                        ans[i][j]=ans[i-1][j]
                    else:
                        ans[i][j]=ans[i-1][j]+1
                else:
                    if s[i][j]==s[i][j-1]:
                        a=ans[i][j-1]
                    else:
                        a=ans[i][j-1]+1
                    if s[i][j]==s[i-1][j]:
                        b=ans[i-1][j]
                    else:
                        b=ans[i-1][j]+1
                    ans[i][j]=min(a,b)
    A=ans[h-1][w-1]
    if A%2==1:
        print(A//2+1)
    else:
        print(A//2)
        
if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
from collections import deque


def solve(h, w, s_list):
    # cost_map
    cost = [[1000] * w for _ in range(h)]
    cost[0][0] = 0
    # find how many flip
    queue = deque([(0, 0)])
    while len(queue) > 0:
        i, j = queue.popleft()
        if i < h - 1:
            if s_list[i][j] != s_list[i + 1][j]:
                new_cost = cost[i][j] + 1
            else:
                new_cost = cost[i][j]
            if new_cost < cost[i + 1][j]:
                cost[i + 1][j] = new_cost
                queue.append((i + 1, j))
        if j < w - 1:
            if s_list[i][j] != s_list[i][j + 1]:
                new_cost = cost[i][j] + 1
            else:
                new_cost = cost[i][j]
            if new_cost < cost[i][j + 1]:
                cost[i][j + 1] = new_cost
                queue.append((i, j + 1))

    res = (cost[h - 1][w - 1] + 1) // 2
    # print(cost)
    # black-black not admitted
    if s_list[0][0] == "#" and s_list[h - 1][w - 1] == "#":
        res += 1
    return res


def main():
    h, w = map(int, input().split())
    s_list = [list(input()) for _ in range(h)]
    res = solve(h, w, s_list)
    print(res)


def test():
    assert solve(3, 3, [[".", "#", "#"], [".", "#", "."], ["#", "#", "."]]) == 1
    assert solve(2, 2, [["#", "."], [".", "#"]]) == 2


if __name__ == "__main__":
    test()
    main()

Submission status: Accepted

Solution code:
h, w = map(int, input().split())
field = [[c for c in input().strip()] for _ in range(h)]
sx, sy = 0, 0
gx, gy = w - 1, h - 1
dirx = [1, 0]
diry = [0, 1]
inf = 1001001001
dp = [[(inf, False) for _ in range(w)] for _ in range(h)]
flip = False
step = 0
for i in range(w):
    if field[0][i] == '.':
        if flip:
            step += 1
            flip = False
    elif field[0][i] == '#':
        if flip == False:
            flip = True
    dp[0][i] = (step, flip)

flip = False
step = 0
for i in range(h):
    if field[i][0] == '.':
        if flip:
            step += 1
            flip = False
    elif field[i][0] == '#':
        if flip == False:
            flip = True
    dp[i][0] = (step, flip)

for i in range(1, h):
    for j in range(1, w):
        tmp1, f1 = dp[i - 1][j]
        tmp2, f2 = dp[i][j - 1]
        if field[i][j] == '.':
            if f1:
                tmp1 += 1
                #f1 = False
            if f2:
                tmp2 += 1
                #f2 = False
            dp[i][j] = (min(tmp1, tmp2), False)
        else:
            if i == gy and j == gx:
                dp[i][j] = (min(tmp1 + 1, tmp2 + 1), True)
            else:
                dp[i][j] = (min(tmp1, tmp2), True)

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

Submission status: Accepted

Solution code:
import sys
import collections

sys.setrecursionlimit(10 ** 8)

input = sys.stdin.readline


def main():
    H, W = [int(x) for x in input().split()]
    S = [list(input().strip()) for _ in range(H)]

    ans = 0
    f = False
    if S[0][0] == '#':
        ans += 1
        f = True

    q = collections.deque()
    q.append([[0, 0], 0, f])

    d = [[10 ** 9] * W for j in range(H)]

    while q:
        c = q.pop()
        dist = c[1]
        fl = c[2]

        j = c[0][0]
        i = c[0][1]

        if d[j][i] <= dist:
            continue
        else:
            d[j][i] = dist

        if i != W - 1:
            if S[j][i + 1] == '#':
                if fl:
                    q.append([[j, i + 1], dist, True])
                else:
                    q.append([[j, i + 1], dist + 1, True])
            else:
                q.append([[j, i + 1], dist, False])

        if j != H - 1:
            if S[j + 1][i] == '#':
                if fl:
                    q.append([[j + 1, i], dist, True])
                else:
                    q.append([[j + 1, i], dist + 1, True])
            else:
                q.append([[j + 1, i], dist, False])

    ans += d[H - 1][W - 1]

    print(ans)

if __name__ == '__main__':
        main()

Submission status: Accepted

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

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

arr = []
for h in range(H):
  s = list(input())
  arr.append(s)

if arr[0][0] == "#":
  dp[0][0] = 1
  
for h in range(H):
  for w in range(W):
    if h == 0:
      if w != 0:
        a = arr[h][w]
        b = arr[h][w-1]
        if a == b or a == ".":
          dp[h][w] = dp[h][w-1]
        else:
          dp[h][w] = dp[h][w-1] + 1
 
    else:      
      if w == 0:
        a = arr[h][w]
        b = arr[h-1][w]
        if  a == b or a == ".":
          dp[h][w] = dp[h-1][w]
        else:
          dp[h][w] = dp[h-1][w] + 1

      else:
        a = arr[h][w] 
        b = arr[h][w-1]
        c = arr[h-1][w]
        if a == "." or (a == b and a == c):
          dp[h][w] = min(dp[h][w-1],dp[h-1][w])
        elif a == b:
          dp[h][w] = dp[h][w-1]
        elif a == c:
          dp[h][w] = dp[h-1][w]
        else:
          dp[h][w] = min(dp[h][w-1] + 1,dp[h-1][w]+1)
    
print(dp[H-1][W-1])

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
import sys
import heapq
from collections import deque

def solve(H: int, W: int, s: "List[str]"):
    minScore = 10**16
    def isBlock(x,y):
        return s[y][x] == "#"
    first = isBlock(0,0)
    current = set([(0,0)])
    next = set()
    map = [[None for j in range(H)] for i in range(W)]
    map[0][0] = (1,True) if first else (0,False)
    def addNextIfCan(x,y,prevScore,prevBlock):
        if x >= W or y >= H:
            return
        c = isBlock(x,y)
        next.add((x,y))
        cScore = prevScore + 1 if c and not prevBlock else prevScore
        if map[x][y] == None:
            map[x][y] = (cScore,c)
        if map[x][y][0] > cScore:
            map[x][y] = (cScore,c)
        elif c and map[x][y][0] == cScore:
            map[x][y] = (cScore,c)
    while len(current) > 0:
        while len(current) > 0:
            n = current.pop()
            prevScore = map[n[0]][n[1]][0]
            prevBlock = map[n[0]][n[1]][1]
            addNextIfCan(n[0]+1,n[1],prevScore,prevBlock)
            addNextIfCan(n[0],n[1]+1,prevScore,prevBlock)
        current = next
        next = set()
    print(map[W-1][H-1][0])
    return


# Generated by 1.1.6 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 bisect
from collections import Counter, deque
# import copy
# from heapq import heappush, heappop, heapify
# from fractions import gcd
# import itertools
# from operator import attrgetter, itemgetter
# import math

import sys

# import numpy as np

readline = sys.stdin.readline
MOD = 10 ** 9 + 7
INF = float('INF')
sys.setrecursionlimit(10 ** 5)


def main():
    h, w = list(map(int, readline().split()))

    s = [input() for _ in range(h)]
    n = [[INF] * w for _ in range(h)]

    que1 = deque()
    que2 = deque()

    if s[0][0] == "#":
        n[0][0] = 1
        que2.append((0, 0))
    else:
        n[0][0] = 0
        que1.append((0, 0))

    wall = 0
    while True:
        while que1:
            y, x = que1.popleft()
            ny = y + 1
            nx = x + 1
            if y == h - 1 and x == w - 1:
                print(wall)
                sys.exit()

            if ny < h and n[ny][x] == INF:
                if s[ny][x] == "#":
                    n[ny][x] = min(n[ny][x], wall + 1)
                    que2.append((ny, x))
                elif s[ny][x] == ".":
                    n[ny][x] = min(n[ny][x], wall)
                    que1.append((ny, x))

            if nx < w and n[y][nx] == INF:
                if s[y][nx] == "#":
                    n[y][nx] = min(n[y][nx], wall + 1)
                    que2.append((y, nx))
                elif s[y][nx] == ".":
                    n[y][nx] = min(n[y][nx], wall)
                    que1.append((y, nx))

        wall += 1
        while que2:
            y, x = que2.popleft()
            ny = y + 1
            nx = x + 1
            if y == h - 1 and x == w - 1:
                print(wall)
                sys.exit()

            if ny < h and n[ny][x] == INF:
                if s[ny][x] == "#":
                    n[ny][x] = min(n[ny][x], wall)
                    que2.append((ny, x))
                elif s[ny][x] == ".":
                    n[ny][x] = min(n[ny][x], wall)
                    que1.append((ny, x))

            if nx < w and n[y][nx] == INF:
                if s[y][nx] == "#":
                    n[y][nx] = min(n[y][nx], wall + 1)
                    que2.append((y, nx))
                elif s[y][nx] == ".":
                    n[y][nx] = min(n[y][nx], wall)
                    que1.append((y, nx))

    print(n[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=[]
ch=[]
for _ in range(h):
    tempDP=[]
    tempCh=[]
    for _ in range(w):
        tempCh.append(0)
        tempDP.append(0)
    dp.append(tempDP)
    ch.append(tempCh)

#startposi
if s[0][0]=="#":
    dp[0][0]=1
    ch[0][0]=1

for x in range(1,w):
    if s[0][x]=="#":
        ch[0][x] = 1
        if ch[0][x-1]==1:
            dp[0][x] = dp[0][x-1]
        else:
            dp[0][x] = dp[0][x-1]+1
    else:
        dp[0][x] = dp[0][x - 1]

for y in range(1,h):
    if s[y][0]=="#":
        ch[y][0] = 1
        if ch[y-1][0]==1:
            dp[y][0] = dp[y-1][0]
        else:
            dp[y][0] = dp[y-1][0]+1
    else:
        dp[y][0] = dp[y-1][0]


for y in range(1,h):
    for x in range(1,w):
        if s[y][x]==".":
            dp[y][x]=min(dp[y][x-1],dp[y-1][x])
        else:
            ch[y][x]=1
            if ch[y-1][x]==1:
                dp[y][x]=dp[y-1][x]
            else:
                dp[y][x]=dp[y-1][x]+1

            if ch[y][x-1]==1:
                dp[y][x]=min(dp[y][x],dp[y][x-1])
            else:
                dp[y][x]=min(dp[y][x],dp[y][x-1]+1)


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

Submission status: Accepted

Solution code:
h,w = map(int,input().split())
lst = [[0]*w for _ in range(h)]
tile = []
for i in range(h):
    tile.append(list(input()))
if tile[0][0] == '#':
    lst[0][0] = 1
for j in range(1,w):
    if tile[0][j] == '.':
        if lst[0][j-1] % 2 == 0:
            lst[0][j] = lst[0][j-1]
        else:
            lst[0][j] = lst[0][j-1] + 1
    else:
        if lst[0][j-1] % 2 == 0:
            lst[0][j] = lst[0][j-1] + 1
        else:
            lst[0][j] = lst[0][j-1]
for i in range(1,h):
    if tile[i][0] == '.':
        if lst[i-1][0] % 2 == 0:
            lst[i][0] = lst[i-1][0]
        else:
            lst[i][0] = lst[i-1][0] + 1
    else:
        if lst[i-1][0] % 2 == 0:
            lst[i][0] = lst[i-1][0] + 1
        else:
            lst[i][0] = lst[i-1][0]
for i in range(1,h):
    for j in range(1,w):
        if tile [i][j] == '.':
            if lst[i][j-1] % 2 == 0:
                a = lst[i][j-1]
            else:
                a = lst[i][j-1] + 1
            if lst[i-1][j] % 2 == 0:
                b = lst[i-1][j] 
            else:
                b = lst[i-1][j] + 1
            lst[i][j] = min(a,b)
        else:
            if lst[i][j-1] % 2 == 0:
                a = lst[i][j-1] + 1
            else:
                a = lst[i][j-1]
            if lst[i-1][j] % 2 == 0:
                b = lst[i-1][j] + 1 
            else:
                b = lst[i-1][j]
            lst[i][j] = min(a,b)
print(-(-lst[h-1][w-1]//2))

Submission status: Accepted

Solution code:
H,W=map(int,input().split())
M=[[0 for i in range(W)] for i in range(H)]
for _ in range(H):
    s=input()
    for i in range(W):
        if s[i]=='#':
            M[_][i]=1
dp=[[10**6 for i in range(W)] for i in range(H)]
if M[0][0]==1:
    dp[0][0]=1
else:
    dp[0][0]=0
for j in range(W-1):
    if M[0][j+1]==0:
        dp[0][j+1]=dp[0][j]
    else:
        if M[0][j]==1:
            dp[0][j+1]=dp[0][j]
        else:
            dp[0][j+1]=dp[0][j]+1
for i in range(H-1):
    if M[i+1][0]==0:
        dp[i+1][0]=dp[i][0]
    else:
        if M[i][0]==1:
            dp[i+1][0]=dp[i][0]
        else:
            dp[i+1][0]=dp[i][0]+1
for i in range(1,H):
    for j in range(0,W-1):
        if M[i][j+1]==0:
            dp[i][j+1]=min(dp[i-1][j+1],dp[i][j])
        elif M[i][j+1]==1:
            if M[i-1][j+1]==1:
                if M[i][j]==1:
                    dp[i][j+1]=min(dp[i-1][j+1],dp[i][j])
                else:
                    dp[i][j+1]=min(dp[i-1][j+1],dp[i][j]+1)
            else:
                if M[i][j]==1:
                    dp[i][j+1]=min(dp[i-1][j+1]+1, dp[i][j])
                else:
                    dp[i][j+1]=min(dp[i-1][j+1]+1,dp[i][j]+1)
print(dp[H-1][W-1])

Submission status: Accepted

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

# print(S)

INF = 10 ** 6

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

# print(dp)

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

        if S[i][j] == "#":
            flip = 1
        else:
            flip = 0

        if i == 0:
            if S[i][j - 1] == "#":
                flip = 0
            dp[i][j] = dp[i][j - 1] + flip
        elif j == 0:
            if S[i - 1][j] == "#":
                flip = 0
            dp[i][j] = dp[i - 1][j] + flip
        else:
            flip1 = 0
            flip2 = 0
            if flip == 1 and (S[i - 1][j] == "."):
                flip1 = 1
            if flip == 1 and S[i][j - 1] == ".":
                flip2 = 1

            dp[i][j] = min(dp[i - 1][j] + flip1, dp[i][j - 1] + flip2)

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

Submission status: Accepted

Solution code:
H, W = map(int, input().split())
maze = [list(input()) for _ in range(H)]
done = [[10**4 + 1]*(W) for _ in range(H)]

min_count = 10 ** 4 + 1

def dfs(h, w, before_black, count):
    if maze[h][w] == "#":
        is_black = True
        if not before_black:
            count += 1
    else:
        is_black = False
    if done[h][w] <= count:
        return
    done[h][w] = count
    if h == H-1 and w == W-1:
        global min_count
        if count < min_count:
            min_count = count
    elif h == H-1:
        dfs(h, w+1, is_black, count)
    elif w == W-1:
        dfs(h+1, w, is_black, count)
    else:
        dfs(h+1, w, is_black, count)
        dfs(h, w+1, is_black, count)

dfs(0,0,False,0)
print(min_count)

Submission status: Accepted

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

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

for y in range(H):
    for x in range(W):
        cand = []
        if y > 0:
            if s[y][x] == s[y-1][x]:
                cand.append(dq[y-1][x])
            else:
                cand.append(dq[y-1][x]+1)
        if x > 0:
            if s[y][x] == s[y][x-1]:
                cand.append(dq[y][x-1])
            else:
                cand.append(dq[y][x-1]+1)
        if cand:
            dq[y][x] = min(cand)

n = dq[H-1][W-1]

if s[0][0] == ".":
    if s[H-1][W-1] == ".":
        print(n//2)
    else:
        print((n+1)//2)
else:
    if s[H-1][W-1] == ".":
        print((n+1)//2)
    else:
        print((n+2)//2)

Submission status: Accepted

Solution code:
h,w = (int(x) for x in input().split())
ab = []
for _ in range(h):
    a = input()
    a = a+'#'
    ab.append(list(a))
ab.append(list('#'*w))
dp = [[100000000000000000 for a in range(w+1)] for b in range(h+1)]
if ab[0][0] == '#':
    dp[0][0] = 1
else:
    dp[0][0] = 0
step = [[0, 0]]
 
while len(step) > 0:
    y, x = step.pop(0)
    
    if h-1<y or w-1<x :continue
    
    if dp[y+1][x] == 100000000000000000:
        step.append([y+1, x])
    if dp[y][x+1] == 100000000000000000:
        step.append([y, x+1])

    if ab[y][x+1] == '#' and ab[y][x] == '.' :
        dp[y][x+1] = min(dp[y][x] + 1, dp[y][x+1])
    else:
        dp[y][x+1] = min(dp[y][x],dp[y][x+1])
    
    if ab[y+1][x] == '#' and ab[y][x] == '.' :
        dp[y+1][x] = min(dp[y][x] + 1, dp[y+1][x])
    else:
        dp[y+1][x] = min(dp[y][x], dp[y+1][x])
    
 
print(dp[h-1][w-1])

Submission status: Accepted

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

dp = [[0] * W for _ in range(H)]
for y in range(H):
    for x in range(W):
        if y-1 < 0 and x-1 < 0:
            dp[y][x] = int(S[y][x] != '.')
        elif y-1 < 0:
            dp[y][x] = dp[y][x-1] + (S[y][x] != S[y][x-1])
        elif x-1 < 0:
            dp[y][x] = dp[y-1][x] + (S[y][x] != S[y-1][x])
        else:
            dp[y][x] = min(dp[y-1][x] + (S[y][x] != S[y-1][x]),
                           dp[y][x-1] + (S[y][x] != S[y][x-1]))


#print('\n', *dp, sep='\n')

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

Submission status: Accepted

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

dp[0][0] = 1 if maze[0][0] == "#" else 0

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

for i in range(1, W):
    dp[0][i] = dp[0][i - 1] if maze[0][i] == maze[0][i - 1] else dp[0][i - 1] + 1 if maze[0][i] == "#" else dp[0][i - 1]


for h in range(1, H):
    for w in range(1, W):
        cand_1 = dp[h - 1][w] if maze[h][w] == maze[h - 1][w] else dp[h - 1][w] + 1 if maze[h][w] == "#" else dp[h - 1][w]
        cand_2 = dp[h][w - 1] if maze[h][w] == maze[h][w - 1] else dp[h][w - 1] + 1 if maze[h][w] == "#" else dp[h][w - 1]
        dp[h][w] = min(cand_1, cand_2)

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

Submission status: Accepted

Solution code:
h, w = map(int, input().split())
s = [input() for _ in range(h)] # #.のグリッドの場合
seen = [[0] * w for _ in range(h)]
seen[0][0] = 1
dp = [[99] * w for _ in range(h)]
dp[0][0] = 0
current = '.'

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

from collections import deque
step = [(0,1), (0,-1), (1,0), (-1,0)]
que = deque()
que.append((0, 0))
#import numpy as np
while que:
    x, y = que.popleft()
    for tx, ty in step:
        current = s[x][y]
        xi, yi = x + tx, y + ty
        if xi < 0 or yi < 0 or xi >= h or yi >= w:
            continue
        if s[xi][yi] == s[x][y]:
            dp[xi][yi] = min(dp[x][y], dp[xi][yi])
            if seen[xi][yi] == 0:
                seen[xi][yi] = seen[x][y] + 1
                que.append((xi, yi))
        if s[xi][yi] != s[x][y]:
            if s[xi][yi] == '.':
                dp[xi][yi] = min(dp[x][y], dp[xi][yi])
            else:
                dp[xi][yi] = min(dp[x][y]+1, dp[xi][yi])
            if seen[xi][yi] == 0:
                seen[xi][yi] = seen[x][y] + 1
                que.append((xi, yi))
    #print(np.array(seen))
#print(np.array(dp))
print(dp[h-1][w-1])

Submission status: Accepted

Solution code:
H, W = map(int, input().split())
grid = [input() for _ in range(H)]
dp = [[10**9] * (W+1) for _ in range(H+1)]

dp[0][1] = dp[1][0] = 0
  
for i in range(1, H+1):
  for j in range(1, W+1):
    if grid[i-1][j-1] == '.':
      dp[i][j] = min(dp[i-1][j], dp[i][j-1])
    else:
      dp[i][j] = min(dp[i-1][j], dp[i][j-1]) + 1
      if i >= 2 and grid[i-2][j-1] == '#':
        dp[i][j] =  min(dp[i][j], dp[i-1][j])
      if j >= 2 and grid[i-1][j-2] == '#':
        dp[i][j] =  min(dp[i][j], dp[i][j-1])
print(dp[-1][-1])

Submission status: Accepted

Solution code:
from collections import deque

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

def dfs():
    ope = [[201]*w for _ in range(h)]
    if maze[0][0] == '.':
        ope[0][0] = 0
    else:
        ope[0][0] = 1

    que = deque([])
    que.append((0,0))

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

    while que:
        (x,y) = que.popleft()
        for i in range(2):
            nx = x + dx[i]
            ny = y + dy[i]
            t = ope[x][y]
            if nx < h and ny < w:
                if ope[nx][ny] == 201:
                    que.append((nx,ny))
                if maze[x][y] == '.' and maze[nx][ny] == '#':
                    ope[nx][ny] = min(ope[nx][ny],t + 1)
                else:
                    ope[nx][ny] = min(ope[nx][ny],t)
    return ope[h-1][w-1]
print(dfs())

Submission status: Accepted

Solution code:

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

grid = tuple(tuple(map(lambda x: x == '.',input())) for _ in range(H))


dp = [float('inf')]*W
dp[0] = 0
prow = [True]*W
for row in grid:
    ndp = [None]*W
    ndp[0] = dp[0] + int(prow[0] and not row[0])
    for i in range(1,W):
        ndp[i] = min(ndp[i-1]+int(row[i-1] and not row[i]),dp[i]+int(prow[i] and not row[i]))
    prow = row
    dp = ndp

print(dp[-1])

Submission status: Accepted

Solution code:
from collections import deque

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

count = 0
color = S[0][0]
Q1 = deque()
Q2 = deque()
if color == '#':
  count += 1
done = set((0, 0))

Q1.append((0, 0))

while True:
  while Q1:
    x, y = Q1.popleft()
    if x == W-1 and y == H-1:
      break
    for dx, dy in [(1, 0), (0, 1)]:
      if x+dx >= W or y+dy >= H:
        continue
      if (x+dx, y+dy) in done:
        continue
      done.add((x+dx, y+dy))
      if S[y+dy][x+dx] == color:
        Q1.append((x+dx, y+dy))
      else:
        Q2.append((x+dx, y+dy))
    else:
      continue
    break
  else:
    Q1, Q2 = Q2, Q1
    if color == '#':
      color = '.'
    else:
      color = '#'
      count += 1
    continue
  break

print(count)

Submission status: Accepted

Solution code:
from functools import lru_cache

H, W = map(int,input().split())
Map = [input() for _ in range(H)]
def black(r,c):
  return 1 if Map[r-1][c-1]=='#' else 0

@lru_cache(maxsize=20000)
def cost(r,c,b0):
  b = black(r,c)
  if b0==0:
    if r==1 and c==1: return b
    elif r==1: return cost(r,c-1,b)
    elif c==1: return cost(r-1,c,b)
    else: return min(cost(r-1,c,b),cost(r,c-1,b))
  elif b0==1 and b==1:
    if r==1 and c==1: return 1
    elif r==1: return cost(r,c-1,b)
    elif c==1: return cost(r-1,c,b)
    else: return min(cost(r-1,c,b),cost(r,c-1,b))
  else:
    if r==1 and c==1: return 1
    elif r==1: return cost(r,c-1,0) +1
    elif c==1: return cost(r-1,c,0) +1
    else: return min(cost(r-1,c,0),cost(r,c-1,0)) +1
    
print(cost(H,W,0))

Submission status: Accepted

Solution code:
import queue
def main():
    h, w = map(int, input().split())
    s = [list(input().rstrip()) for _ in range(h)]
    q = queue.Queue()
    t = [[10**9]*w for _ in range(h)]
    f = [[True]*w for _ in range(h)]
    if s[h-1][w-1] == "#":
        t[h-1][w-1] = 1
    else:
        t[h-1][w-1] = 0
    q.put([h-1, w-1])
    while not q.empty():
        y, x = q.get()
        if y < h-1 and x < w-1:
            py = t[y+1][x]
            if s[y][x] == "#" and s[y+1][x] == ".":
                py += 1
            px = t[y][x+1]
            if s[y][x] == "#" and s[y][x+1] == ".":
                px += 1
            t[y][x] = min(py, px)
        elif y < h-1 and x == w-1:
            py = t[y+1][x]
            if s[y][x] == "#" and s[y+1][x] == ".":
                py += 1
            t[y][x] = py
        elif y == h-1 and x < w-1:
            px = t[y][x+1]
            if s[y][x] == "#" and s[y][x+1] == ".":
                px += 1
            t[y][x] = px
        if 0 < y:
            if f[y-1][x]:
                f[y-1][x] = False
                q.put([y-1, x])
        if 0 < x:
            if f[y][x-1]:
                f[y][x-1] = False
                q.put([y, x-1])
    print(t[0][0])

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
# coding: utf-8
H,W=map(int,input().split())
MAP=[]
d=[]
INF=10**9

for i in range(H):
    line=list(input())
    MAP.append(line)
    d.append([INF for j in range(W)])

if MAP[0][0]==".":
    d[0][0]=0
else:
    d[0][0]=1

for i in range(H):
    for j in range(W):
        if i==0 and j==0:
            continue
        
        if i!=0 and j!=0:
            if MAP[i][j]==".":
                d[i][j]=min(d[i][j-1],d[i-1][j])
                
            else: 
                if MAP[i][j-1]==MAP[i-1][j]==".":
                    d[i][j]=min(d[i][j-1],d[i-1][j])+1
                    
                elif MAP[i][j-1]==MAP[i-1][j]=="#":
                    d[i][j]=min(d[i][j-1],d[i-1][j])
                    
                elif MAP[i][j-1]==".":
                    d[i][j]=min(d[i][j-1]+1,d[i-1][j])
                    
                elif MAP[i-1][j]==".":
                    d[i][j]=min(d[i][j-1],d[i-1][j]+1)
                    
        elif i==0:
            if MAP[i][j]==".":
                d[i][j]=d[i][j-1]
                
            else: 
                if MAP[i][j-1]==".":
                    d[i][j]=d[i][j-1]+1
                    
                elif MAP[i][j-1]=="#":
                    d[i][j]=d[i][j-1]
                    
                elif MAP[i][j-1]==".":
                    d[i][j]=d[i][j-1]+1
                    
        elif j==0:
            if MAP[i][j]==".":
                d[i][j]=d[i-1][j]
                
            else: 
                if MAP[i-1][j]==".":
                    d[i][j]=d[i-1][j]+1
                    
                elif MAP[i-1][j]=="#":
                    d[i][j]=d[i-1][j]
                    
                elif MAP[i-1][j]==".":
                    d[i][j]=d[i-1][j]+1

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

Submission status: Accepted

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

for i in range(H):
    for j in range(W):


        if i != 0:
            if grid[i][j] == grid[i-1][j] or grid[i][j] == '.':
                dp[i][j] = min(dp[i][j],dp[i-1][j])
            else:
                dp[i][j] = min(dp[i][j], dp[i-1][j]+1)

        if j != 0:
            if grid[i][j] == grid[i][j-1] or grid[i][j] == '.':
                dp[i][j] = min(dp[i][j],dp[i][j-1])
            else:
                dp[i][j] = min(dp[i][j], dp[i][j-1]+1)


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

# for i in range(H):
#     print(dp[i])

Submission status: Accepted

Solution code:
import bisect
import math
from collections import deque

def sRaw():
    return input().rstrip("\r")


def iRaw():
    return int(input())


def ssRaw():
    return input().split()


def isRaw():
    return list(map(int, ssRaw()))


INF = 1 << 29


def main():
    H,W  =isRaw()
    ss = [sRaw() for _ in range(H)]
    memo = [[INF for _ in range(W)] for _ in range(H)]
    qu = deque()
    isF = 1 if ss[0][0] == "#" else 0
    ans = INF
    memo[0][0] = isF
    for y in range(H):
        for x in range(W):
            s = ss[y][x]
            if x!=0:
                prevM = memo[y][x-1]
                prevS = ss[y][x-1]
                if s=="#" and prevS!="#":
                    memo[y][x] = min(memo[y][x],prevM+1)
                else:
                    memo[y][x] = min(memo[y][x], prevM)
            if y!=0:
                prevM = memo[y-1][x]
                prevS = ss[y-1][x]
                if s == "#" and prevS != "#":
                    memo[y][x] = min(memo[y][x], prevM+1)
                else:
                    memo[y][x] = min(memo[y][x], prevM)
    return memo[H-1][W-1]

    
if __name__ == "__main__":
    print(main())

Submission status: Accepted

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

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

if S[0][0] == '#':
    board[0][0] = 1

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

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

for i in range(1, H):
    for j in range(1, W):
        if S[i][j] == '.':
            board[i][j] = min(board[i - 1][j], board[i][j - 1])
        else:
            if S[i - 1][j] == '.':
                up = 1
            else:
                up = 0
            if S[i][j - 1] == '.':
                left = 1
            else:
                left = 0
            board[i][j] = min(board[i - 1][j] + up, board[i][j - 1] + left)

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