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


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


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

dp = [[float("inf") for _ in range(W)] for _ in range(H)]

dp[0][0] = 1 if S[0][0] == "#" else 0
d = [(0, 1), (1, 0)]
for i in range(H):
    for j in range(W):
        for dx, dy in d:
            ni = i + dx
            nj = j + dy
            if ni < H and nj < W:
                if S[i][j] == "#" and S[ni][nj] == "#":
                    tmp = dp[i][j]
                else:
                    if S[ni][nj] == "#":
                        tmp = dp[i][j] + 1
                    else:
                        tmp = dp[i][j]
                if tmp < dp[ni][nj]:
                    dp[ni][nj] = tmp

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

Submission status: Accepted

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

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

DR = [1, -1, 0, 0]
DC = [0, 0, 1, -1]

def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()


def main():
    H, W = LI()
    g = []
    for _ in range(H):
        g.append(S())
    dp = [[inf for _ in range(W)] for __ in range(H)]

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

    for r in range(H):
        for c in range(W):
            if r == 0 and c == 0:
                if g[r][c] == '#':
                    dp[r][c] = 1
                else:
                    dp[r][c] = 0
 
            cand1, cand2 = inf, inf
            if 0 <= r-1 < H:
                if g[r-1][c] == '.' and g[r][c] == '#':
                    dp[r][c] = min(dp[r][c], dp[r-1][c] + 1)
                else:
                    dp[r][c] = min(dp[r][c], dp[r-1][c])
            if 0<= c-1 < W:
                if g[r][c-1] == '.' and g[r][c] == '#':
                    dp[r][c] = min(dp[r][c], dp[r][c-1] + 1)
                else:
                    dp[r][c] = min(dp[r][c], dp[r][c-1])
    print(dp[-1][-1])
main()

Submission status: Accepted

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

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

DR = [1, -1, 0, 0]
DC = [0, 0, 1, -1]

def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()


def main():
    H, W = LI()
    g = []
    for _ in range(H):
        g.append(S())
    dp = [[inf for _ in range(W)] for __ in range(H)]

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

    for r in range(H):
        for c in range(W):
            if r == 0 and c == 0:
                if g[r][c] == '#':
                    dp[r][c] = 1
                else:
                    dp[r][c] = 0
 
            cand1, cand2 = inf, inf
            if r-1 >= 0:
                if g[r-1][c] == '.' and g[r][c] == '#':
                    dp[r][c] = min(dp[r][c], dp[r-1][c] + 1)
                else:
                    dp[r][c] = min(dp[r][c], dp[r-1][c])
            if c-1 >= 0:
                if g[r][c-1] == '.' and g[r][c] == '#':
                    dp[r][c] = min(dp[r][c], dp[r][c-1] + 1)
                else:
                    dp[r][c] = min(dp[r][c], dp[r][c-1])
    print(dp[-1][-1])
main()

Submission status: Accepted

Solution code:
def main():
    H, W = map(int, input().split())
    s = []
    for _ in range(H):
        S = input()
        s.append(S)
    dp = [[0] * W for _ in range(H)]
    dp[0][0] = 1 if s[0][0] == '#' else 0 # #だと1にする
    for i in range(1, W):
        dp[0][i] = dp[0][i-1] + 1 if s[0][i] == '#' and s[0][i-1] == '.' else dp[0][i -1]
    for i in range(1, H):
        dp[i][0] = dp[i-1][0] + 1 if s[i][0] == '#' and s[i-1][0] == '.' else dp[i-1][0]
    for i in range(1, H):
        for j in range(1, W):
            if s[i][j] == '.':
                dp[i][j] = min(dp[i][j-1], dp[i-1][j])
            else:
                u = dp[i-1][j]
                r = dp[i][j-1]
                if s[i-1][j] == '.':
                    u += 1
                if s[i][j-1] == '.':
                    r += 1
                dp[i][j] = min(u, r)
    return dp[-1][-1]

print(main())

Submission status: Accepted

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

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

DR = [1, -1, 0, 0]
DC = [0, 0, 1, -1]

def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()


def main():
    H, W = LI()
    g = []
    for _ in range(H):
        g.append(S())
    dp = [[inf for _ in range(W)] for __ in range(H)]

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

    for r in range(H):
        for c in range(W):
            cand1, cand2 = inf, inf
            if r-1 >= 0:
                if g[r-1][c] == '.' and g[r][c] == '#':
                    dp[r][c] = min(dp[r][c], dp[r-1][c] + 1)
                else:
                    dp[r][c] = min(dp[r][c], dp[r-1][c])
            if c-1 >= 0:
                if g[r][c-1] == '.' and g[r][c] == '#':
                    dp[r][c] = min(dp[r][c], dp[r][c-1] + 1)
                else:
                    dp[r][c] = min(dp[r][c], dp[r][c-1])
    print(dp[-1][-1])
main()

Submission status: Accepted

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

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

DR = [1, -1, 0, 0]
DC = [0, 0, 1, -1]

def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()


def main():
    H, W = LI()
    g = []
    for _ in range(H):
        g.append(S())
    dp = [[inf for _ in range(W)] for __ in range(H)]

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

    for r in range(H):
        for c in range(W):
            if r != H-1:
                if g[r][c] == '.' and g[r+1][c] == '#':
                    dp[r+1][c] = min(dp[r+1][c], dp[r][c] + 1)
                else:
                    dp[r+1][c] = min(dp[r+1][c], dp[r][c])
            if c != W-1:
                if g[r][c] == '.' and g[r][c+1] == '#':
                    dp[r][c+1] = min(dp[r][c+1], dp[r][c] + 1)
                else:
                    dp[r][c+1] = min(dp[r][c+1], dp[r][c])
    print(dp[-1][-1])
main()

Submission status: Accepted

Solution code:
h, w = map(int, input().split())
lst = [['*' for i in range(w+2)]]
for i in range(h):
    lsti = ['*']
    lsti.extend(list(input()))
    lsti.append('*')
    lst.append(lsti)
lst.append(['*' for i in range(w+2)])

lst_cnt = [[300 for i in range(w+2)] for j in range(h+2)]
if lst[1][1] == '#': lst_cnt[1][1] = -1
else: lst_cnt[1][1] = 0

for i in range(1, h+1):
    for j in range(1, w+1):
        if i == 1 and j == 1: continue
        if lst[i][j] == '.':
            lst_cnt[i][j] = min(abs(lst_cnt[i-1][j]), abs(lst_cnt[i][j-1]))
        else:
            if lst[i-1][j] == '#':
                kouho1 = lst_cnt[i-1][j]
            else:
                kouho1 = -(lst_cnt[i-1][j]+1)
            if lst[i][j-1] == '#':
                kouho2 = lst_cnt[i][j-1]
            else:
                kouho2 = -(lst_cnt[i][j-1]+1)
            lst_cnt[i][j] = -min(abs(kouho1), abs(kouho2))

print(abs(lst_cnt[h][w]))

Submission status: Accepted

Solution code:
from collections import deque
H, W = map(int, input().split())
s = [list(input()) for _ in range(H)]
dist = [[10**6 for _ in range(W)] for _ in range(H)]

dist[0][0] = 0

q = deque([(0, 0)])
while q:
	h, w = q.pop()

	if h < H-1:
		if s[h][w] == "." and s[h+1][w] == "#":
			if dist[h+1][w] > dist[h][w] + 1:
				dist[h+1][w] = dist[h][w] + 1
				q.appendleft((h+1, w))
		else:
			if dist[h+1][w] > dist[h][w]:
				dist[h+1][w] = min(dist[h+1][w], dist[h][w])
				q.append((h+1, w))

	if w < W-1:
		if s[h][w] == "." and s[h][w+1] == "#":
			if dist[h][w+1] > dist[h][w] + 1:
				dist[h][w+1] = dist[h][w] + 1
				q.appendleft((h, w+1))
		else:
			if dist[h][w+1] > dist[h][w]:
				dist[h][w+1] = dist[h][w]
				q.append((h, w+1))

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

Submission status: Accepted

Solution code:
inf=float("inf")
h,w=map(int,input().split())
D=[[inf]*w for _ in range(h)]
D[0][0]=0

S=[list(input()) for _ in range(h)]
for i in range(h):
    for j in range(w):
        for x,y in ((1,0),(0,1)):
            X,Y=i+x,j+y
            if 0<=X<h and 0<=Y<w:
                if S[i][j]=="." and S[X][Y]=="#":D[X][Y]=min(D[i][j]+1,D[X][Y])
                else:D[X][Y]=min(D[i][j],D[X][Y])

#import numpy as np
#print(np.array(D))
ans=D[h-1][w-1]
print(ans if S[0][0]!="#" else ans+1)

Submission status: Accepted

Solution code:
h,w=map(int,input().split())
d=[0]+[300]*w
for i in range(h):
  s=input()
  if i==0:
    a=s[0]
  for j in range(w):
    t=s[j]==a
    d[j]+=t^(d[j]%2==0)
    if j>0:
      d[j]=min(d[j],d[j-1]+t^(d[j-1]%2==0))
print((d[-2]+(a=="#")+1)//2)

Submission status: Accepted

Solution code:
def main():
  H,W = map(int,input().split())
  S = [input() for _ in range(H)]
  
  dp = [[float('inf') for _ in range(W)] for _ in range(H)]
  if S[0][0] == '#':
    dp[0][0] = 1
  else:
    dp[0][0] = 0
  for i in range(H):
    for j in range(W):
      if j > 0:
        if S[i][j-1] == '.' and S[i][j] == '#':
          dp[i][j] = min(dp[i][j],dp[i][j-1]+1)
        else:
          dp[i][j] = min(dp[i][j],dp[i][j-1])
      if i > 0:
        if S[i-1][j] == '.' and S[i][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])
  print(dp[H-1][W-1])

main()

Submission status: Accepted

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

dp=[[1000]*(w+1) for _ in range(h+1)]

#(1,1)が白か黒か確かめ、黒の場合は+1
if s[0][0]=='.':
    dp[0][0]=0
else:
    dp[0][0]=1

for i in range(h):
    for j in range(w):
        if i-1>=0:
#h（縦）に対して、白⇒黒の場合はdp[i][j]は+1、そうでなければ同じ。
            dp[i][j]=dp[i-1][j]+(1 if s[i-1][j]=='.' and s[i][j]=='#' else 0)
        if j-1>=0:
#w（横）に対して、白⇒黒の場合はdp[i][j]は+1、そうでなければ同じ。
            dp[i][j]=min(dp[i][j],dp[i][j-1]+(1 if s[i][j-1]=='.' and s[i][j]=='#' else 0))

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

Submission status: Accepted

Solution code:
INF = 10**10


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

def next_field (a):
    ret = []
    if a[0] < H-1 :
        ret.append((a[0] + 1, a[1]))
    
    if a[1] < W-1:
        ret.append((a[0], a[1] + 1))
    
    return ret

field = {}
dist = {}
for h in range(H):
    f = input()
    for w, c in enumerate(f):
        field[(h,w)] = c
        dist[(h,w)] = INF

s = set()

if field[(0,0)] == ".":
    dist[(0,0)] = 0
else:
    dist[(0,0)] = 1

s.add((0,0))

while len(s) > 0:
    cur = s.pop()

    for nxt in next_field(cur):

        if field[cur] == field[nxt] or field[nxt] == ".":
            dist[nxt] = min(dist[nxt], dist[cur])
        else:
            dist[nxt] = min(dist[nxt], 1 + dist[cur])

        s.add(nxt)
    
print(dist[(H-1,W-1)])

Submission status: Accepted

Solution code:
from itertools import count, repeat

h = int(input().split()[0])
a0 = repeat('.')
r0 = count()
for i in range(h):
  a = input()
  r = [i]
  for x, y, z, u in zip(a0, '.' + a, a, r0):
    r.append(min(u + (x > z), r[-1] + (y > z)))
  a0 = a
  r0 = r[1:]
print(r[-1])

Submission status: Accepted

Solution code:
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
from bisect import bisect_right, bisect_left
import random
from itertools import permutations, accumulate, combinations, product
from re import split
import sys
import string
from bisect import bisect_left, bisect_right
from math import factorial, ceil, floor, gamma, log
from operator import mul
from functools import reduce
from copy import deepcopy
import re

sys.setrecursionlimit(2147483647)
INF = 10 ** 20
def LI(): return list(map(int, sys.stdin.buffer.readline().split()))
def I(): return int(sys.stdin.buffer.readline())
def LS(): return sys.stdin.buffer.readline().rstrip().decode('utf-8').split()
def S(): return sys.stdin.buffer.readline().rstrip().decode('utf-8')
def IR(n): return [I() for i in range(n)]
def LIR(n): return [LI() for i in range(n)]
def SR(n): return [S() for i in range(n)]
def LSR(n): return [LS() for i in range(n)]
def SRL(n): return [list(S()) for i in range(n)]
def MSRL(n): return [[int(j) for j in list(S())] for i in range(n)]
mod = 10 ** 9 + 7


h, w = LI()
L = SR(h)
dp = [[INF] * w for _ in range(h)]
dp[0][0] = 1 if L[0][0] == '#' else 0
for y in range(h):
    for x in range(w):
        if y:
            if L[y][x] == '.' or L[y - 1][x] == '#':
                dp[y][x] = dp[y - 1][x]
            else:
                dp[y][x] = dp[y - 1][x] + 1
        if x:
            if L[y][x] == '.' or L[y][x - 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:
from itertools import count, repeat

h = int(input().split()[0])
a0 = repeat('.')
r0 = count()
for i in range(h):
  a = input()
  r = [i]
  for x, y, z, u in zip(a0, '.' + a, a, r0):
    r.append(min(u + (x + z == '.#'), r[-1] + (y + z == '.#')))
  a0 = a
  r0 = r[1:]
print(r[-1])

Submission status: Accepted

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

s = []
for i in range(h):
    s.append([1 if i == "#" else 0 for i in list(input())])
cost = [[0]*w for _ in range(h)]
cost[0][0] = s[0][0]

for i in range(1, h):
    if s[i-1][0] == 0 and s[i][0] == 1:
        cost[i][0] = cost[i-1][0] + 1
    else:
        cost[i][0] = cost[i-1][0]
for i in range(1, w):
    if s[0][i-1] == 0 and s[0][i] == 1:
        cost[0][i] = cost[0][i-1] + 1
    else:
        cost[0][i] = cost[0][i-1]

for i in range(1, h):
    for j in range(1, w):
        if s[i-1][j] == 0 and s[i][j] == 1:
            cost_down = cost[i-1][j] + 1
        else:
            cost_down = cost[i-1][j]
        if s[i][j-1] == 0 and s[i][j] == 1:
            cost_right = cost[i][j-1] + 1
        else:
            cost_right = cost[i][j-1]
        cost[i][j] = min(cost_down, cost_right)

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

Submission status: Accepted

Solution code:
h, w = map(int, input().split())
a0 = '.' * w
r0 = range(w)
for i in range(h):
  a = input()
  r = [i]
  for x, y, z, u in zip(a0, '.' + a, a, r0):
    r.append(min(u + (x + z == '.#'), r[-1] + (y + z == '.#')))
  a0 = a
  r0 = r[1:]
print(r[-1])

Submission status: Accepted

Solution code:
h, w = map(int, input().split())
a0 = '.' * w
r0 = list(range(w))
for i in range(h):
  a = input()
  r = [i]
  for x, y, z, u in zip(a0, '.' + a, a, r0):
    r.append(min(u + (x + z == '.#'), r[-1] + (y + z == '.#')))
  a0 = a
  r0 = r[1:]
print(r[-1])

Submission status: Accepted

Solution code:
h,w = map(int,input().split())
L = []
dp = []
for i in range(h):
    d = [0]*w
    dp.append(d)
M = []
for i in range(h):
    s = input()
    M.append(s)
if M[0][0] == '#':
    dp[0][0] = 1
for i in range(h):
    for j in range(w):
        if i == 0 and j == 0:
            None
        elif i == 0:
            if M[i][j-1] == '.' and M[i][j] == '#':
                dp[i][j] = dp[i][j-1]+1
            else:
                dp[i][j] = dp[i][j-1]
        elif j == 0:
            if M[i-1][j] == '.' and M[i][j] == '#':
                dp[i][j] = dp[i-1][j]+1
            else:
                dp[i][j] = dp[i-1][j]
        else:
            k = 0
            l = 0
            if M[i-1][j] == '.' and M[i][j] == '#':
                k = 1
            if M[i][j-1] == '.' and M[i][j] == '#':
                l = 1
            dp[i][j] = min(dp[i-1][j]+k, dp[i][j-1]+l)
print(dp[h-1][w-1])

Submission status: Accepted

Solution code:

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

grid = [[v for v in input()] for _ in range(H)]

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

DX = [0, 1]
DY = [1, 0]
##移動
dp[0][0] = 0

for x in range(H):
    for y in range(W):
        for dx, dy in zip(DX, DY):
            nx = x+dx#移動後
            ny = y+dy
            if 0 <= nx < H and 0 <= ny < W:
                if grid[x][y] == "." and grid[x][y] != grid[nx][ny]:
                    dp[nx][ny] = min(dp[nx][ny], dp[x][y]+1)
                else:
                    dp[nx][ny] = min(dp[nx][ny], dp[x][y])
if grid[0][0] == "#":
    dp[-1][-1] += 1
print(dp[-1][-1])

Submission status: Accepted

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

for i in range(1, W):
    dp[0][i] = dp[0][i-1] + (int(s[0][i]=="#") if s[0][i-1]=="." else 0)
for h in range(1,H):
  dp[h][0] = dp[h-1][0] + (int(s[h][0]=="#") if s[h-1][0]=="." else 0)
  for w in range(1,W):
    dp[h][w] = min(dp[h-1][w]+(int(s[h][w]=="#") if s[h-1][w]=="." else 0), 
    dp[h][w-1]+(int(s[h][w]=="#") if s[h][w-1]=="." else 0))
print(dp[-1][-1])

Submission status: Accepted

Solution code:
import sys
input = lambda: sys.stdin.readline().rstrip() 

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

    ans = [[0]*W for _ in range(H)]
    if s[0][0]=='#':
        ans[0][0] = 1
    for i in range(1, W+H-1):
        for y in range(max(0, i-(W-1)), min(i+1, H)):
            x = i-y
            if y==0:
                if s[y][x-1]=='.' and s[y][x]=='#':
                    ans[y][x] = ans[y][x-1] + 1
                else:
                    ans[y][x] = ans[y][x-1]
            elif x==0:
                if s[y-1][x]=='.' and s[y][x]=='#':
                    ans[y][x] = ans[y-1][x] + 1
                else:
                    ans[y][x] = ans[y-1][x]
            else:
                if s[y][x]=='#':
                    ans[y][x] = min(ans[y-1][x]+(1 if s[y-1][x]=='.' else 0), ans[y][x-1]+(1 if s[y][x-1]=='.' else 0))
                else:
                    ans[y][x] = min(ans[y-1][x], ans[y][x-1])
    print(ans[-1][-1])

if __name__ == '__main__':
    resolve()

Submission status: Accepted

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

domain[0][0]= int(s[0][0]=="#")

for x in range(1,h):
    domain[x][0] = domain[x-1][0] + (int(s[x][0]=="#") if s[x-1][0]=="." else 0)
for y in range(1, w):
    domain[0][y] = domain[0][y-1] + int(s[0][y]=="#" if s[0][y-1]=="." else 0)
    for x in range(1,h):
        domain[x][y]= min(
            domain[x-1][y] + int(s[x][y]=="#" if s[x-1][y]=="." else 0),
            domain[x][y-1] + int(s[x][y]=="#" if s[x][y-1]=="." else 0)
        )

print(domain[-1][-1])

Submission status: Accepted

Solution code:
inp = list(map(lambda x: int(x), input().split(" ")))
H = inp[0]
W = inp[1]

field = [""]*H

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

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

if (field[0][0] == "#"):
    dp[0][0] = 1

for i in range(H):
    for j in range(W):
        check1 = 0
        check2 = 0
        if (i>0 and j>0):
            if (field[i][j]=="#" and field[i-1][j]=="."):
                check1 = 1
            if (field[i][j]=="#" and field[i][j-1]=="."):
                check2 = 1
            dp[i][j] = min(dp[i-1][j]+check1, dp[i][j-1]+check2)
        elif (i>0 and j==0):
            if (field[i][j]=="#" and field[i-1][j]=="."):
                check1 = 1
            dp[i][j] = dp[i-1][j]+check1
        elif (i==0 and j>0):
            if (field[i][j]=="#" and field[i][j-1]=="."):
                check2 = 1
            dp[i][j] = dp[i][j-1]+check2

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

Submission status: Accepted

Solution code:
h, w = map(int, input().split())
a0 = '.' * w
r0 = [200] * w
for i in range(h):
  a = input()
  r = [i and 200]
  for x, y, z, u in zip(a0, '.' + a, a, r0):
    r.append(min(u + (x + z == '.#'), r[-1] + (y + z == '.#')))
  a0 = a
  r0 = r[1:]
print(r[-1])

Submission status: Accepted

Solution code:
h, w = map(int, input().split())
a0 = '.' * w
r0 = [200] * w
for i in range(h):
  a = input()
  r = [i * 200]
  for x, y, z, u in zip(a0, '.' + a, a, r0):
    r.append(min(u + (x + z == '.#'), r[-1] + (y + z == '.#')))
  a0 = a
  r0 = r[1:]
print(r[-1])

Submission status: Accepted

Solution code:
def main():
    H, W = map(int, input().split())
    s = []
    for _ in range(H):
        S = input()
        s.append(S)
    dp = [[0] * W for _ in range(H)]
    dp[0][0] = 1 if s[0][0] == '#' else 0
    for i in range(1, W):
        dp[0][i] = dp[0][i-1] + 1 if s[0][i] == '#' and s[0][i-1] == '.' else dp[0][i -1]
    for i in range(1, H):
        dp[i][0] = dp[i-1][0] + 1 if s[i][0] == '#' and s[i-1][0] == '.' else dp[i-1][0]
    for i in range(1, H):
        for j in range(1, W):
            if s[i][j] == '.':
                dp[i][j] = min(dp[i][j-1], dp[i-1][j])
            else:
                u = dp[i-1][j]
                r = dp[i][j-1]
                if s[i-1][j] == '.':
                    u += 1
                if s[i][j-1] == '.':
                    r += 1
                dp[i][j] = min(u, r)
    return dp[-1][-1]
print(main())

Submission status: Accepted

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

grid = [[v for v in input()] for _ in range(H)]

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

DX = [0, 1]
DY = [1, 0]

dp[0][0] = 0

for x in range(H):
    for y in range(W):
        for dx, dy in zip(DX, DY):
            nx = x+dx
            ny = y+dy
            if 0 <= nx < H and 0 <= ny < W:
                if grid[x][y] == "." and grid[x][y] != grid[nx][ny]:
                    dp[nx][ny] = min(dp[nx][ny], dp[x][y]+1)
                else:
                    dp[nx][ny] = min(dp[nx][ny], dp[x][y])
if grid[0][0] == "#":
    dp[-1][-1] += 1
print(dp[-1][-1])

Submission status: Accepted

Solution code:
from collections import deque

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

dp=[[1000]*(w+1) for _ in range(h+1)]

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

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

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

Submission status: Accepted

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

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

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

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

Submission status: Accepted

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

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

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

for i in range(H):
    for j in range(W):
        if j:
            if (s[i][j - 1] == ".") and (s[i][j] == "#"):
                dp[i][j] = min(dp[i][j], dp[i][j - 1] + 1)
            else:
                dp[i][j] = min(dp[i][j], dp[i][j - 1])
        if i:
            if (s[i - 1][j] == ".") and (s[i][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])

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

Submission status: Accepted

Solution code:
H, W = map(int, input().split())
def change(x):   # 黒なら1, 白なら0   ※しなくてもよい
    if x == '#':
        return 1
    else:
        return 0
field = list()
for i in range(H):
    field.append(list(map(change,[i for i in input()])))

# 右と横に移動するベクトル
vector = [[1, 0], [0, 1]]

# 座標(i, j)に到達したか確認するリスト　未到達: 0 到達: 1 
check_list = [[0 for _ in range(W)] for _ in range(H)]
check_list[0][0] = 1

# 座標(i, j)に到達するために操作が何回か必要か記録するリスト
count_list = [[0 for _ in range(W)] for _ in range(H)]
count_list[0][0] = field[0][0]

# 座標(i, j)に到達する際、どのマスから来るのが最善か記録するリスト
zahyo_front = [[0] * W] * H
zahyo_front[0][0] = [0, 0]

# 探索候補の座標を記録するリスト   ※Queueモジュールなど使うと簡易になるらしい
# １つ目のfor文 i番目のk個目の候補の座標はzahyo_search[k][i]
zahyo_search = [[(0, 0)]]


for i in range(H+W-2):
    zahyo = zahyo_search[i]   # i番目の探索候補の座標を取り出す
    zahyo_kari = list()       # (i+1)回目の探索候補の座標を記録する仮リスト
    for (y, x) in zahyo:
        for (dy, dx) in vector:
            count = count_list[y][x]  
            y_k = y + dy
            x_k = x + dx
            try:               # if y_k < H and x_k < W: でもよい 
                
                if field[y_k][x_k] == 1 and field[y][x] == 0: 
                    
                    count += 1
                    # (y_k, x_k)が黒かつ(y, x)が白ならば連続でないので、countを+1する
                
                if check_list[y_k][x_k] == 0:        # (y_k, x_k)に未到達なら、そのまま記録する 
                    count_list[y_k][x_k] = count
                    zahyo_front[y_k][x_k] = [y, x]
                    check_list[y_k][x_k] = 1
                    zahyo_kari.append((y_k, x_k))    # (i+1)回目の探索候補の仮リストに入れる
                    
                else:                                # (y_k, x_k)に到達済
                    if count < count_list[y_k][x_k]:  # countが記録されていたものより小さければ採用
                        count_list[y_k][x_k] = count
                        zahyo_front[y_k][x_k] = [y, x]
                        
            except:
                pass
            
    zahyo_search.append(zahyo_kari) # 仮リストを探索リストに入れる

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

Submission status: Accepted

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

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

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

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

    res = dp[H - 1][W - 1]
    print(res)
    return


if __name__ == '__main__':
    main()

Submission status: Accepted

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

Submission status: Accepted

Solution code:

#####

import numpy as np
# from numpy import int32, int8
# from collections import deque

#####

def getIntList(inp):
	return [int(_) for _ in inp]


from sys import stdin
import sys
sys.setrecursionlimit(10**8)

def getInputs():
	inputs=[]
	for line in stdin:
		line=line.split()
		inputs.append(line)
	return inputs



def main(inputs):
	h,w=getIntList(inputs[0])
	colors=np.empty((h,w),np.bool)
	for hi in range(h):
		for wi in range(w):
			colors[hi,wi]=inputs[1+hi][0][wi]=="."

# 	h=20
# 	w=20
# 	np.random.seed(0)
# 	colors=np.random.randint(0,2,(h,w))

# 	from matplotlib import pyplot as plt
# 	for hi in range(h):
# 		for wi in range(w):
# 			plt.annotate(str((hi,wi)), (wi-0.5,hi), color="g")
# 	plt.imshow(colors)
# 	plt.show()
			
# 	print(colors.astype(np.int32))
	
	flipSize=np.empty((h,w), np.int32)
	
	if colors[0,0]: flipSize[0,0]=0
	else: flipSize[0,0]=1
	
	for hi in range(h):
		for wi in range(w):
			if hi==0 and wi==0: continue
			c=colors[hi,wi]
			fs=[]
			if hi>0:
				d=int(colors[hi-1,wi] and (not c))
				s=flipSize[hi-1, wi]+d
				fs.append(s)
				
			if wi>0:
				d=int(colors[hi,wi-1] and (not c))
				s=flipSize[hi, wi-1]+d
				fs.append(s)
			
			fs=min(fs)
			flipSize[hi,wi]=fs
	
	print(flipSize[h-1,w-1])
	

if __name__=="__main__":
	inputs=getInputs()
# 	inputs=simInputs()
	main(inputs)

Submission status: Accepted

Solution code:
import heapq

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

field = [input() for _ in range(h)]

todo = [[0, 0, 0, '.']]
seen = [[10**5] * w for _ in range(h)]
while todo:
    count, y, x, color = heapq.heappop(todo)
    if field[y][x] == color:
        pass
    else:
        if color == '.':
            count += 1
        color = field[y][x]

    if seen[y][x] <= count:
        continue
    seen[y][x] = count

    slide_right = [count, y, x+1, color]
    slide_down = [count, y+1, x, color]
    if x+1 < w:
        heapq.heappush(todo, slide_right)
    if y+1 < h:
        heapq.heappush(todo, slide_down)

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