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())
grid = [input() for _ in range(H)]
dp = [[float('inf')]*(W) for _ in range(H)]
dp[0][0] = 0 if grid[0][0] == '.' else 1
for i in range(H):
    for k in range(W):
        if i+1 < H:
            if grid[i][k] == '.' and grid[i+1][k] == '#':
                dp[i+1][k] = min(dp[i][k]+1,dp[i+1][k])
            else:
                dp[i+1][k] = min(dp[i][k],dp[i+1][k])
        if k+1 < W:
            if grid[i][k] == '.' and grid[i][k+1] == '#':
                dp[i][k+1] = min(dp[i][k]+1,dp[i][k+1])
            else:
                dp[i][k+1] = min(dp[i][k],dp[i][k+1])
print(dp[-1][-1])

Submission status: Accepted

Solution code:
H,W=map(int,input().split());M=[input()for _ in"_"*H];D=[[0]*-~W for _ in"_"*-~H];m=999
for i in range(H):
  for j in range(W):D[i+1][j+1]=min([m,D[i][j+1]+(M[i-1][j]>M[i][j])][i>0],[m,D[i+1][j]+(M[i][j-1]>M[i][j])][j>0],m*(i+j>0))
print(D[-1][-1]+(M[0][0]<"."))

Submission status: Accepted

Solution code:
H,W=map(int,input().split());M=[input()for _ in"_"*H];D=[[0]*-~W for _ in"_"*-~H]
for i in range(H):
  for j in range(W):
    a=b=999
    if i>0:a=D[i][j+1]+(M[i-1][j]>M[i][j])
    if j>0:b=D[i+1][j]+(M[i][j-1]>M[i][j])
    D[i+1][j+1]=min(a,b,999*(i+j>0))
print(D[-1][-1]+(M[0][0]<"."))

Submission status: Accepted

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

maze = []
for i in range(h):
    t = list(input())
    maze.append(t)
    
dx = [1, 0]
dy = [0, 1]


dp = [[10000]*w for i in range(h)]
if maze[0][0] == "#":
    dp[0][0] = 1
else:
    dp[0][0] = 0

for x in range(w):
    for y in range(h):
        for dxi, dyi in zip(dx, dy):
            if not (0<=x+dxi<w and 0<=y+dyi<h):
                continue
            dp[y+dyi][x+dxi] = min(dp[y+dyi][x+dxi], dp[y][x]+(maze[y][x]=="." and maze[y+dyi][x+dxi]=="#"))
            
#print(*dp)
print(dp[h-1][w-1])

Submission status: Accepted

Solution code:

def resolve():
    INF = 1 << 60
    H, W = map(int, input().split())
    G = [input() for _ in range(H)]

    # 長方形区域を選んで、その中の通路と壁を反転する操作ができる
    # dp[ y ][ x ] := マス (y, x) に到達するまでに魔法を唱える回数の最小値

    dp = [[INF] * W for _ in range(H)]
    if G[0][0] == "#":
        dp[0][0] = 1
    else:
        dp[0][0] = 0

    # 1, (nx, ny) が通路のとき, 操作なし
    # 2, (nx, ny) か壁で、(x, y) が通路のとき, 操作する
    # 3, (nx, ny) が壁で、(x, y) も壁のとき, 2の操作が継続中

    drc = [(0, 1), (1, 0)]
    for y in range(H):
        for x in range(W):
            for dy, dx in drc:
                ny = y + dy
                nx = x + dx
                if ny >= H or nx >= W:
                    continue
                cost = 0
                if G[ny][nx] == "#" and G[y][x] == ".":
                    cost = 1
                dp[ny][nx] = min(dp[ny][nx], dp[y][x] + cost)

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


if __name__ == "__main__":
    resolve()

Submission status: Accepted

Solution code:

from collections import deque
def resolve():
    INF = 1 << 60
    H, W = map(int, input().split())
    G = [input() for _ in range(H)]

    dist = [[INF] * W for _ in range(H)]
    dist[0][0] = 0 if G[0][0] == "." else 1

    q = deque()
    q.append((dist[0][0], 0, 0))
    drc = [(1, 0), (0, 1)]
    while q:
        cost, y, x = q.popleft()
        for dy, dx in drc:
            ny = y + dy
            nx = x + dx
            if y + dy >= H or x + dx >= W:
                continue
            nx_cost = cost if G[y][x] == G[ny][nx] else cost + 1
            if nx_cost < dist[ny][nx]:
                dist[ny][nx] = nx_cost
                q.append((dist[ny][nx], ny, nx))

    ans = (dist[H - 1][W - 1] + 1) // 2
    print(ans)


if __name__ == "__main__":
    resolve()

Submission status: Accepted

Solution code:
H,W = map(int,input().split())
map = []
INF = 10**8
for _ in range(H):
    map.append(input())

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

for i in range(H):
    for j in range(W):
        if i == 0 and j == 0:
            if map[i][j] == '#':
                dp[i][j] = 1
        elif i == 0:
            flag = 0
            if map[i][j] == '#' and map[i][j-1] == '.':
                flag = 1
            dp[i][j] = flag + dp[i][j-1]
        elif j == 0:
            flag = 0
            if map[i][j] == "#" and map[i-1][j] == ".":
                flag = 1
            dp[i][j] = flag + dp[i-1][j]
        else:
            flag1 = 0
            flag2 = 0
            if map[i][j] == "#" and map[i][j-1] == ".":
                flag1 = 1
            if map[i][j] == "#" and map[i-1][j] == ".":
                flag2 = 1
            dp[i][j] = min(dp[i][j-1]+flag1,dp[i-1][j]+flag2)

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

Submission status: Accepted

Solution code:
H, W=map(int, input().split())
S=[]
from math import ceil

for h in range(H):
    s=list(input())
    S.append(s)

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

for h in range(H):
    for w in range(W):
        if w==0 and h==0:
            continue
        if h==0:
            if S[h][w] == S[h][w-1]:
                now=0
            else:
                now=1
            dp[h][w]=min(dp[h][w-1]+now, dp[h][w])
        elif w==0:
            if S[h][w] == S[h-1][w]:
                now=0
            else:
                now=1
            dp[h][w]=min(dp[h-1][w]+now, dp[h][w])
        else:
            if S[h][w]==S[h][w-1]:
                noww = 0
            else:
                noww=1
            if S[h][w]==S[h-1][w]:
                nowh = 0
            else:
                nowh=1
            dp[h][w] = min(dp[h][w], dp[h][w-1]+noww, dp[h-1][w]+nowh)
ans = ceil(dp[-1][-1]/2)
print(ans)

Submission status: Accepted

Solution code:
import sys
from collections import deque

input = sys.stdin.readline
H, W = map(int, input().split())

grid = []
for _ in range(H):
    grid.append(list(input().strip()))

q = deque()
# x, y, count, pre color
q.append((0, 0, 1 if grid[0][0] == "#" else 0, grid[0][0]))

visited = [[-1 for _ in range(W)] for _ in range(H)]
ans = float("inf")
while q:
    x, y, count, pre = q.popleft()
    # print(x, y, count, pre)
    v_score = visited[y][x]
    if v_score != -1 and v_score <= count:
        continue
    visited[y][x] = count

    for dx, dy in ((1, 0), (0, 1)):
        nx = x + dx
        ny = y + dy
        nc = count
        if nx < 0 or W <= nx or ny < 0 or H <= ny:
            continue
        n_color = grid[ny][nx]
        if n_color != pre and n_color == "#":
            nc += 1
        if nx == W-1 and ny == H-1:
            ans = min(ans, nc)
            print(ans)
            sys.exit()
        else:
            if visited[ny][nx] != -1 and visited[ny][nx] <= nc:
                continue
            if count == nc:
                q.appendleft((nx, ny, nc, n_color))
            else:
                q.append((nx, ny, nc, n_color))

# print(visited)
print(ans)

Submission status: Accepted

Solution code:
from collections import deque
H,W = map(int,input().split())
A = [input().strip() for _ in range(H)]
d = 0
if A[0][0]=="#":
    d += 1
que = deque([(0,0,d)])
hist = [[H*W for _ in range(W)] for _ in range(H)]
hist[0][0] = d
while que:
    i,j,d = que.popleft()
    if j+1<W and A[i][j+1]==A[i][j]:
        if hist[i][j+1]>d:
            hist[i][j+1] = d
            que.append((i,j+1,d))
    elif j+1<W and A[i][j+1]!=A[i][j]:
        if hist[i][j+1]>d+1:
            hist[i][j+1] = d+1
            que.append((i,j+1,d+1))
    if i+1<H and A[i+1][j]==A[i][j]:
        if hist[i+1][j]>d:
            hist[i+1][j] = d
            que.append((i+1,j,d))
    elif i+1<H and A[i+1][j]!=A[i][j]:
        if hist[i+1][j]>d+1:
            hist[i+1][j] = d+1
            que.append((i+1,j,d+1))
m = hist[H-1][W-1]
print((m+1)//2)

Submission status: Accepted

Solution code:
from collections import deque
H,W = map(int,input().split()); INF = float("inf")
G = []
for i in range(H):
  temp = str(input()); temp = list(temp)
  G.append(temp)

dp = [[INF]*W for _ in range(H)]
dp[0][0] = 0
if G[0][0] == "#":
  dp[0][0] += 1
for i in range(H):
  for j in range(W):
    #横への遷移
    if j+1 <= W-1: #一番右以外
      if G[i][j] == "." and G[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])
    #下への遷移
    if i+1 <= H-1: #一番右以外
      if G[i][j] == "." and G[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])
#print(dp)
ans = dp[-1][-1]
print(ans)

Submission status: Accepted

Solution code:
h,w=map(int,input().split())
s=[list(input()) for i in range(h)]
dp=[[0]*w for _ in range(h)]
if s[0][0]=="#":
    dp[0][0]=1
for i in range(w-1):
    if s[0][i]=="." and s[0][i+1]=="#":
        dp[0][i+1]=dp[0][i]+1
    else:
        dp[0][i+1]=dp[0][i]
for i in range(h-1):
    if s[i][0]=="." and s[i+1][0]=="#":
        dp[i+1][0]=dp[i][0]+1
    else:
        dp[i+1][0]=dp[i][0]
for i in range(1,h):
    for j in range(1,w):
        v=0
        g=0
        if s[i-1][j]=="." and s[i][j]=="#":
            v=1
        if s[i][j-1]=="." and s[i][j]=="#":
            g=1

        dp[i][j]=min(dp[i-1][j]+v,dp[i][j-1]+g)
print(dp[h-1][w-1])

Submission status: Accepted

Solution code:
H, W = map(int,input().split())
MAP = []
INF = 10 ** 8
for _ in range(H):
    MAP.append(input())
 
dp = [[0 for i in range(W)] for i in range(H)]
 
for i in range(H):
    for j in range(W):
        if i == 0 and j == 0:
            if MAP[i][j] == "#":
                dp[i][j] = 1
        elif i == 0:
            flag = 0
            if MAP[i][j] == "#" and MAP[i][j-1] == ".":
                flag = 1
            dp[i][j] = flag + dp[i][j-1]
        elif j == 0:
            flag = 0
            if MAP[i][j] == "#" and MAP[i-1][j] == ".":
                flag = 1
            dp[i][j] = flag + dp[i-1][j]
        else:
            flag1 = 0
            flag2 = 0
            if MAP[i][j] == "#" and MAP[i][j-1] == ".":
                flag1 = 1
            if MAP[i][j] == "#" and MAP[i-1][j] == ".":
                flag2 = 1
            dp[i][j] = min(dp[i][j-1]+flag1,dp[i-1][j]+flag2)
        
 
print(dp[H-1][W-1])

Submission status: Accepted

Solution code:
from typing import List, Dict

INF = 10**9+1


def read_int() -> int:
    return int(input().strip())


def read_ints() -> List[int]:
    return list(map(int, input().strip().split(' ')))


def solve() -> int:
    H, W = read_ints()
    S: List[str] = []
    for _ in range(H):
        S.append(input().strip())
    black_count = [[INF for _ in range(W)] for _ in range(H)]
    if S[0][0] == '.':
        black_count[0][0] = 0
    else:
        black_count[0][0] = 1

    for i in range(H):
        for j in range(W):
            if i == 0 and j == 0:
                continue
            if S[i][j] == '.':
                if i > 0:
                    black_count[i][j] = min(black_count[i][j], black_count[i-1][j])
                if j > 0:
                    black_count[i][j] = min(black_count[i][j], black_count[i][j-1])
            else:
                if i > 0:
                    if S[i-1][j] == '.':
                        black_count[i][j] = min(black_count[i][j], black_count[i-1][j]+1)
                    else:
                        black_count[i][j] = min(black_count[i][j], black_count[i-1][j])
                if j > 0:
                    if S[i][j-1] == '.':
                        black_count[i][j] = min(black_count[i][j], black_count[i][j-1]+1)
                    else:
                        black_count[i][j] = min(black_count[i][j], black_count[i][j-1])
    return black_count[H-1][W-1]


if __name__ == '__main__':
    print(solve())

Submission status: Accepted

Solution code:
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time, copy

sys.setrecursionlimit(10**7)
inf = 10**20
mod = 10**9 + 7

stdin = sys.stdin

ni = lambda: int(ns())
na = lambda: list(map(int, stdin.readline().split()))
ns = lambda: stdin.readline().rstrip()  # ignore trailing spaces

h, w = na()
m = []
m = [ns() for _ in range(h)]
dp = [[inf] * w for _ in range(h)]
dp[0][0] = int(m[0][0] == '#')
for x in range(1, w):
    dp[0][x] = dp[0][x-1] + (int(m[0][x]=="#") if m[0][x-1]=="." else 0)
for y in range(1, h):
    dp[y][0] = dp[y-1][0] + (int(m[y][0]=="#") if m[y-1][0]=="." else 0)
    for x in range(1, w):
        dp[y][x] = min(
            dp[y][x-1] + (int(m[y][x]=="#") if m[y][x-1]=="." else 0),
            dp[y-1][x] + (int(m[y][x]=="#") if m[y-1][x]=="." else 0)
        )
print(dp[-1][-1])

Submission status: Accepted

Solution code:
import math
from functools import lru_cache

@lru_cache(maxsize = None)
def count_change_point_min(r , c , current_color):
    min_values = list()
    if r != h-1:
        min_values.append(count_change_point_min(r+1, c, S[r][c]))
    if c != w-1:
        min_values.append(count_change_point_min(r, c+1, S[r][c]))
    if len(min_values) == 0:
        min_values.append(0)
        
    return min(min_values) + (0 if S[r][c] == current_color else 1)
    
    
h,w = map(int,input().split())
S = list()
for _ in range(h):
    S.append(list(input()))
    
if S[0][0] == ".":
    ceil_or_floor = math.floor
else:
    ceil_or_floor = math.ceil
    
print (ceil_or_floor((count_change_point_min(0, 0, S[0][0])+1) / 2))

Submission status: Accepted

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

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

for j in range(w):
    for i in range(h):
        if i == 0 and j == 0:
            if s[i][j] == '#':
                black[i][j] = 1
            else:
                black[i][j] = 0

        if i > 0 and j == 0:
            if s[i][j] == '#':
                if s[i - 1][j] == '#':
                    black[i][j] = black[i - 1][j]
                else:
                    black[i][j] = black[i - 1][j] + 1
            else: # s[i][j] == '.'
                black[i][j] = black[i - 1][j]
                    
        if i == 0 and j > 0:
            if s[i][j] =='#':
                if s[i][j - 1] =='#':
                    black[i][j] = black[i][j - 1]
                else:
                    black[i][j] = black[i][j - 1] + 1
            else:
                    black[i][j] = black[i][j - 1]
                    
        if i > 0 and j > 0:
            if s[i][j] =='#':
                if s[i][j - 1] =='#' and s[i - 1][j] == '#':
                    black[i][j] = min(black[i][j - 1], black[i - 1][j])
                elif s[i][j - 1] =='#'and s[i - 1][j] == '.':
                    black[i][j] = min(black[i][j - 1], black[i - 1][j] + 1)
                elif s[i][j - 1] =='.'and s[i - 1][j] == '#':
                    black[i][j] = min(black[i][j - 1] + 1, black[i - 1][j])
                else:
                    black[i][j] = min(black[i][j - 1] + 1, black[i - 1][j] + 1)
            else:
                    black[i][j] = min(black[i][j - 1], black[i - 1][j])
                
print(black[h-1][w-1])

Submission status: Accepted

Solution code:
import sys
from sys import exit
from collections import deque
from bisect import bisect_left, bisect_right, insort_left, insort_right #func(リスト,値)
from heapq import heapify, heappop, heappush
from itertools import product, permutations, combinations, combinations_with_replacement
from functools import reduce
from math import sin, cos, tan, asin, acos, atan, degrees, radians

sys.setrecursionlimit(10**6)
INF = 10**20
eps = 1.0e-20
MOD = 10**9+7

def lcm(x,y):
    return x*y//gcd(x,y)
def lgcd(l):
    return reduce(gcd,l)
def llcm(l):
    return reduce(lcm,l)
def powmod(n,i,mod):
    return pow(n,mod-1+i,mod) if i<0 else pow(n,i,mod)
def div2(x):
    return x.bit_length()
def div10(x):
    return len(str(x))-(x==0)
def perm(n,mod=None):
    ans = 1
    for i in range(1,n+1):
        ans *= i
        if mod!=None:
            ans %= mod
    return ans
def intput():
    return int(input())
def mint():
    return map(int,input().split())
def lint():
    return list(map(int,input().split()))
def ilint():
    return int(input()), list(map(int,input().split()))
def judge(x, l=['Yes', 'No']):
    print(l[0] if x else l[1])
def lprint(l, sep='\n'):
    for x in l:
        print(x, end=sep)
def ston(c, c0='a'):
    return ord(c)-ord(c0)
def ntos(x, c0='a'):
    return chr(x+ord(c0))
class counter(dict):
    def __init__(self, *args):
        super().__init__(args)
    def add(self,x,d=1):
        self.setdefault(x,0)
        self[x] += d
class comb():
    def __init__(self, n, mod=None):
        self.l = [1]
        self.n = n
        self.mod = mod
    def get(self,k):
        l,n,mod = self.l, self.n, self.mod
        k = n-k if k>n//2 else k
        while len(l)<=k:
            i = len(l)
            l.append(l[i-1]*(n+1-i)//i if mod==None else (l[i-1]*(n+1-i)*powmod(i,-1,mod))%mod)
        return l[k]

H,W=mint()
s=[input() for _ in range(H)]
dp=[[0]*W for _ in range(H)]
dp[0][0]=int(s[0][0]=='#')
for i in range(H):
    for j in range(W):
        if i==j==0:
            continue
        tmp = INF
        if i>0:
            tmp = min(tmp,dp[i-1][j]+int(s[i-1][j]=='.' and s[i][j]=='#'))
        if j>0:
            tmp = min(tmp,dp[i][j-1]+int(s[i][j-1]=='.' and s[i][j]=='#'))
        dp[i][j] = tmp
print(dp[H-1][W-1])

Submission status: Accepted

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

Submission status: Accepted

Solution code:
h,w=map(int,input().split())
m=[]
for i in range(h):
  m.append(list(map(lambda x:int(x=="#"),list(input())))+[0])
m.append([0 for i in range(w+1)])
s=[[100000 for i in range(w+1)] for j in range(h+1)]
s[-1][0]=0
for i in range(h):
  for j in range(w):
    s[i][j]=min(s[i-1][j]+(not(m[i-1][j]) and m[i][j]),s[i][j-1]+(not(m[i][j-1]) and m[i][j]))
print(s[-2][-2])

Submission status: Accepted

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

ans = [[10000]*w for _ in range(h)]
ans[0][0] = 0 if grid[0][0] == "." else 1

queue = deque([(0, 0)])

while len(queue) > 0:
    x, y = queue.popleft()

    for xo, yo in [(0, 1), (1, 0)]:
        xnext, ynext = x+xo, y+yo

        if xnext >= w or ynext >= h:
            continue

        if grid[y][x] == "." and grid[ynext][xnext] == "#":
            if ans[y][x] + 1 < ans[ynext][xnext]:
                ans[ynext][xnext] = ans[y][x] + 1
                queue.append((xnext, ynext))
        else:
            if ans[y][x] < ans[ynext][xnext]:
                ans[ynext][xnext] = ans[y][x]
                queue.append((xnext, ynext))

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

Submission status: Accepted

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

dp = [[10000]*w for _ in range(h)]
dp[0][0] = 0 if grid[0][0] == "." else 1

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

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

Submission status: Accepted

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

from collections import deque
maze=[[10**4]*W for _ in range(H)]
maze[0][0]=1*(S[0][0]=='#')
que=deque([[0,0]])
while que:
    y,x=que.popleft()
    for i,j in [(1,0),(0,1)]:
        nexty,nextx=y+i,x+j
        if nexty>=H or nextx>=W:
            continue
        else:
            if S[y][x]=='.':
                if S[nexty][nextx]=='.':
                    if maze[nexty][nextx]>maze[y][x]:
                        maze[nexty][nextx]=maze[y][x]
                        que.append([nexty,nextx])
                else:
                    if maze[nexty][nextx]>maze[y][x]+1:
                        maze[nexty][nextx]=maze[y][x]+1
                        que.append([nexty,nextx])
            elif S[y][x]=='#':
                if maze[nexty][nextx]>maze[y][x]:
                    maze[nexty][nextx]=maze[y][x]
                    que.append([nexty,nextx])

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

Submission status: Accepted

Solution code:
# https://atcoder.jp/contests/agc043/tasks/agc043_a

import sys
# sys.setrecursionlimit(100000)


def input():
    return sys.stdin.readline().strip()


def input_int():
    return int(input())


def input_int_list():
    return [int(i) for i in input().split()]


ans = (100 * 100) + 1


def main():
    global ans
    h, w = input_int_list()
    grid = []
    grid.append(["#"] * (w + 2))
    for _ in range(h):
        grid.append(["#"] + list(input()) + ["#"])
    grid.append(["#"] * (w + 2))

    dp = [[101 for _ in range(w + 2)] for _ in range(h + 2)]
    if grid[1][1] == "#":
        dp[1][1] = 1
    else:
        dp[1][1] = 0
    for i in range(1, h + 1):
        for j in range(1, w + 1):
            # 上のマスからくる場合を評価
            if i > 1:
                if grid[i - 1][j] == "." and grid[i][j] == "#":
                    dp[i][j] = min(dp[i - 1][j] + 1, dp[i][j])
                else:
                    dp[i][j] = min(dp[i][j], dp[i - 1][j])

            # 左のマスからくる場合を評価
            if j > 1:
                if grid[i][j - 1] == "." and grid[i][j] == "#":
                    dp[i][j] = min(dp[i][j - 1] + 1, dp[i][j])
                else:
                    dp[i][j] = min(dp[i][j - 1], dp[i][j])

    print(dp[h][w])
    return


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
 
H,W = map(int,readline().split())
S = ''.join(read().decode().split())
 
INF = 10 ** 9
N = H*W
U = 250
dp = [[INF] * U for _ in range(N)]
# そのマスをいじる回数 → 総回数の最小値
dp[0] = list(range(U))
for n in range(H*W):
    for i in range(U-1,0,-1):
        if dp[n][i-1]> dp[n][i]:
            dp[n][i-1] = dp[n][i]
    for i in range(1,U):
        if dp[n][i-1] + 1 < dp[n][i]:
            dp[n][i] = dp[n][i-1] + 1
    s = S[n]
    if s == '#':
        for i in range(0,U,2):
            dp[n][i] = INF
    else:
        for i in range(1,U,2):
            dp[n][i] = INF
    x,y = divmod(n,W)
    to = []
    if y < W - 1:
        to.append(n+1)
    if x < H - 1:
        to.append(n+W)
    for m in to:
        for i in range(U):
            if dp[m][i] > dp[n][i]:
                dp[m][i] = dp[n][i]
 
print(min(dp[-1]))

Submission status: Accepted

Solution code:
h, w = map(int, input().split())
hw = [input() for _ in range(h)]
dp = [[1000]*w for _ in range(h)]
if hw[0][0] == "#":
    dp[0][0] = 1
else:
    dp[0][0] = 0

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

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

Submission status: Accepted

Solution code:
H,W=list(map(int,input().split()))
l=[list(input()) for i in range(H)]
inf=10**9
DP=[[inf]*W for i in range(H)]
DP[0][0]=0 if l[0][0]=="." else 1
for i in range(H):
   for j in range(W):
      if i>0:
         DP[i][j]=min(DP[i][j],DP[i-1][j]+1) if l[i-1][j] == "." and l[i][j]=="#" else min(DP[i][j],DP[i-1][j])
      if j>0:
         DP[i][j]=min(DP[i][j],DP[i][j-1]+1) if l[i][j-1] == "." and l[i][j]=="#" else min(DP[i][j],DP[i][j-1])
print(DP[H-1][W-1])

Submission status: Accepted

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

memo = [[10**5]*W for _ in range(H)]
mp = [input() for _ in range(H)]

if mp[0][0] == '#':
  memo[0][0] = 1
else:
  memo[0][0] = 0

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

Submission status: Accepted

Solution code:
import queue
h, w = map(int, input().split())
s = [list(input()) for _ in range(h)]
ans = float('inf')
q = queue.Queue()
vals = [[float('inf')]*w for _ in range(h)]
vals[0][0] = 0
q.put([0, 0])

while not q.empty():
    a = q.get()
    for i, j in ((1, 0), (0, 1)):
        x, y = a[0]+i, a[1]+j
        if 0 <= x < h and 0 <= y < w:
            if s[x][y] == '#' and s[a[0]][a[1]] == '.':
                if vals[x][y] > vals[a[0]][a[1]]+1:
                    vals[x][y] = vals[a[0]][a[1]]+1
                    q.put([x, y])
            elif vals[x][y] > vals[a[0]][a[1]]:
                vals[x][y] = vals[a[0]][a[1]]
                q.put([x, y])
ans = vals[-1][-1]
if s[0][0] == '#':
    ans += 1

print(ans)

Submission status: Accepted

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

#solution:dp

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

def update(dp, i, j, ni, nj):
    if s[ni][nj]=='.':
        dp[ni][nj]=min(dp[i][j],dp[ni][nj])
    elif s[i][j]=='#':
        dp[ni][nj]=min(dp[i][j],dp[ni][nj])
    else:
        dp[ni][nj]=min(dp[i][j]+1,dp[ni][nj])
    
for i in range(h):
    for j in range(w):
        if i+1<h:
            update(dp,i,j,i+1,j)
        if j+1<w:
            update(dp,i,j,i,j+1)
print(dp[h-1][w-1])

Submission status: Accepted

Solution code:
import collections
H, W, *S = open(0).read().split()
H, W = [int(_) for _ in [H, W]]
dist = [[float('inf')] * W for _ in range(H)]
dist[0][0] = 0
Q = collections.deque([0])
while True:
    if not Q:
        break
    i = Q.popleft()
    x, y = divmod(i, W)
    d = dist[x][y]
    for dx, dy in ((1, 0), (0, 1)):
        nx, ny = x + dx, y + dy
        if 0 <= nx < H and 0 <= ny < W:
            if S[nx][ny] == '#' and S[x][y] == '.':
                if dist[nx][ny] > d + 1:
                    dist[nx][ny] = d + 1
                    Q += [nx * W + ny]
            elif dist[nx][ny] > d:
                dist[nx][ny] = d
                Q += [nx * W + ny]
ans = dist[-1][-1]
if S[0][0] == '#':
    ans += 1
print(ans)

Submission status: Accepted

Solution code:
H, W = map(int, input().split())
stage = []
scores = []
for _ in range(H):
    stage.append(list(input()))
    scores.append([float('inf')] * W)
if stage[0][0] == '#':
    scores[0][0] = 1
else:
    scores[0][0] = 0
move = [[0, 1], [1, 0]]
for y in range(H):
    for x in range(W):
        for dx, dy in move:
            nx, ny = x + dx, y + dy
            if H <= ny or W <= nx:
                continue
            if stage[ny][nx] == '#' and stage[y][x] == '.':
                scores[ny][nx] = min(scores[ny][nx], scores[y][x] + 1)
            else:
                scores[ny][nx] = min(scores[ny][nx], scores[y][x])
# print(*scores, sep='\n')
print(scores[-1][-1])

Submission status: Accepted

Solution code:


def submit():
    h, w = map(int, input().split())
    s = [input() for _ in range(h)]

    # dpで解く
    # dp[i][j] : マス(i, j)に至るまでに必要な最小flip回数
    dp = [
        [float('inf') for _ in range(w)] for _ in range(h)
    ]
    dp[0][0] = 0 if s[0][0] == "." else 1

    def update(dp, i, j, ni, nj):
        if s[ni][nj] == ".":
            dp[ni][nj] = min(dp[i][j], dp[ni][nj])
        elif s[i][j] == "#":
            dp[ni][nj] = min(dp[i][j], dp[ni][nj])
        else: # 次が黒であり、今が白である => flip必要回数が増える
            dp[ni][nj] = min(dp[i][j] + 1, dp[ni][nj])
    
    for i in range(h):
        for j in range(w):
            if i + 1 < h:
                update(dp, i, j, i + 1, j)
            if j + 1 < w:
                update(dp, i, j, i, j + 1)

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


submit()

Submission status: Accepted

Solution code:
H,W = map(int,input().split())
grid = [[0] for _ in range(H)]
for i in range(H):
    grid[i] = input()
dp = [[float('inf')]*W for _ in range(H)]
if grid[0][0] == '.':
    dp[0][0] = 0
else:
    dp[0][0] = 1
for y in range(H):
    for x in range(W):
        if x > 0:
            if grid[y][x-1] == '.' and grid[y][x] == '#':
                dp[y][x] = min(dp[y][x],dp[y][x-1]+1)
            else:
                dp[y][x] = min(dp[y][x],dp[y][x-1])
        if y > 0:
            if grid[y-1][x] == '.' and grid[y][x] == '#':
                dp[y][x] = min(dp[y][x],dp[y-1][x]+1)
            else:
                dp[y][x] = min(dp[y][x],dp[y-1][x])
print(dp[-1][-1])

Submission status: Accepted

Solution code:
h, w = map(int, input().split())
s = [[i == "#" for i in input()] for _ in range(h)]
dp = [[10**9] * w for _ in range(h)]
dp[0][0] = int(s[0][0])
for i in range(h):
    for j in range(w):
        a = dp[i - 1][j] + (not s[i - 1][j] and s[i][j])
        b = dp[i][j - 1] + (not s[i][j -1] and s[i][j])
        dp[i][j] = min(a, b,dp[i][j])
print(dp[-1][-1])