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:
# -*- coding: utf-8 -*-
h,w = list(map(int,input().split()))
board = []
for _ in range(h):
    board.append(list(input()))
inf=float("inf")
dp = [[inf] * w for _ in range(h)]

if board[0][0]==".":
    dp[0][0]=0
else:
    dp[0][0]=1
#1列目を計算
for i in range(1,w):
    pre = board[0][i-1]
    if board[0][i]==".":
        dp[0][i]=dp[0][i-1]
    else:
        if pre==board[0][i]:
            dp[0][i]=dp[0][i-1]
        else:
            dp[0][i]=dp[0][i-1]+1
#2列目移行を計算
for i in range(1,h):
    for j in range(w):
        if j==0:
            if board[i][j]=="#" and board[i-1][j]==".":
                dp[i][j]=dp[i-1][j]+1
            else:
                dp[i][j]=dp[i-1][j]
        else:
            if board[i][j]=="#":
                left_add = 0
                up_add = 0
                if board[i][j-1]==".":
                    left_add=1
                if board[i-1][j]==".":
                    up_add=1
                dp[i][j]=min(dp[i-1][j]+up_add,dp[i][j-1]+left_add)
            else:
                dp[i][j]=min(dp[i-1][j],dp[i][j-1])
print(dp[-1][-1])

Submission status: Accepted

Solution code:
import sys
from collections import deque
readline = sys.stdin.readline
H, W = map(int, readline().split())
G = [list(map(lambda x: 1 if x == '.' else 0, readline().strip())) for _ in range(H)]

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

Q = deque([(0, 0)])
used = set(Q)
dim = [(0, 1), (1, 0)]
while Q:
    nx, ny = Q.pop()
    for dx, dy in dim:
        fx, fy = nx+dx, ny+dy
        if not 0 <= fx < H or not 0 <= fy < W:
            continue
        if (fx, fy) in used:
            continue
        used.add((fx, fy))
        if G[nx][ny] == G[fx][fy]:
            dist[fx][fy] = dist[nx][ny]
            Q.append((fx, fy))
        else:
            dist[fx][fy] = 1 + dist[nx][ny]
            Q.appendleft((fx, fy))

K = dist[H-1][W-1]
if G[0][0] == 0:
    K += 1
if G[H-1][W-1] == 0:
    K += 1
print(K//2)

Submission status: Accepted

Solution code:
h, w = map(int, input().split())
cells = []
for hh in range(h):
    row = list(input())
    cells.append(row)
#print(cells)

dp = [[0 for c in range(w)] for r in range(h)]

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

r = 0
for c in range(1,w):
    if cells[r][c] != cells[r][c-1] and cells[r][c] == "#":
        dp[r][c] = dp[r][c-1] + 1
    else:
        dp[r][c] = dp[r][c-1]
c = 0        
for r in range(1,h):
    if cells[r][c] != cells[r-1][c] and cells[r][c] == "#":
        dp[r][c] = dp[r-1][c] + 1
    else:
        dp[r][c] = dp[r-1][c]

for r in range(1,h):
    for c in range(1,w):
        upper = dp[r-1][c]
        if cells[r][c] != cells[r-1][c] and cells[r][c] == '#':
            upper += 1
        left = dp[r][c-1]
        if cells[r][c] != cells[r][c-1] and cells[r][c] == '#':
            left += 1
        dp[r][c] = min(left, upper)
print(dp[-1][-1])

Submission status: Accepted

Solution code:
def examA():
    def bfs_grid(h, w, s, maze):
        distance = [[inf] * w for _ in range(h)]

        def bfsg():
            queue = deque()
            if maze[s[0]][s[1]]=="#":
                queue.append((s, 1))
                distance[s[0]][s[1]] = 1
            else:
                queue.append((s,0))
                distance[s[0]][s[1]] = 0
            while len(queue):
                [y, x],st = queue.popleft()
                for i in range(2):
                    nx, ny = x + [1, 0][i], y + [0, 1][i]
                    if (0 <= nx < w and 0 <= ny < h):
                        cur = deepcopy(distance[y][x])
                        if st==0 and maze[ny][nx]=='#':
                            cur += 1
                        if distance[ny][nx] <= cur:
                            continue
                        if maze[ny][nx]=='#':
                            queue.append(((ny, nx),1))
                        else:
                            queue.append(((ny, nx), 0))
                        distance[ny][nx] = cur
            return distance

        return bfsg()
    H, W = LI()
    S = [SI()for _ in range(H)]
    L = bfs_grid(H,W,[0,0],S)
    ans = L[-1][-1]
    #print(L)
    print(ans)
    return

def examB():
    ans = 0
    print(ans)
    return

def examC():
    ans = 0
    print(ans)
    return

def examD():
    ans = 0
    print(ans)
    return

def examE():
    ans = 0
    print(ans)
    return

def examF():
    ans = 0
    print(ans)
    return

import sys,bisect,itertools,heapq,math,random
from copy import deepcopy
from heapq import heappop,heappush,heapify
from collections import Counter,defaultdict,deque
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))
def LSI(): return list(map(str,sys.stdin.readline().split()))
def LS(): return sys.stdin.readline().split()
def SI(): return sys.stdin.readline().strip()
global mod,mod2,inf,alphabet,_ep
mod = 10**9 + 7
mod2 = 998244353
inf = 10**18
_ep = 10**(-12)
alphabet = [chr(ord('a') + i) for i in range(26)]

sys.setrecursionlimit(10**6)

if __name__ == '__main__':
    examA()

"""

"""

Submission status: Accepted

Solution code:
import sys
import itertools
input = sys.stdin.readline
sys.setrecursionlimit(100000)
mod = 10 ** 9 + 7

def read_values(): return map(int, input().split())
def read_index(): return map(lambda x: int(x) - 1, input().split())
def read_list(): return list(read_values())
def read_lists(N): return [read_list() for n in range(N)]


class v:
    def __init__(self, f):
        self.f = f
        self.v = None
 
    def __str__(self):
        return str(self.v)
 
    def ud(self, n):
        if self.v is None:
            self.v = n
        else:
            self.v = self.f(self.v, n) 


def main():
    H, W = read_values()
    F = ["." * (W + 2)] + ["." + input() + "." for _ in range(H)] + ["." * (W + 2)]
    dp = [[10 ** 10 for _ in range(W + 2)] for __ in range(H + 2)]
    dp[1][0] = 0
    dp[0][1] = 0
    for h in range(1, H + 1):
        for w in range(1, W + 1):
            if F[h][w] == ".":
                dp[h][w] = min(dp[h - 1][w], dp[h][w - 1])
            else:
                hr = 0 if F[h - 1][w] == "#" else 1
                wr = 0 if F[h][w - 1] == "#" else 1
                dp[h][w] = min(dp[h - 1][w] + hr, dp[h][w - 1] + wr)
    print(dp[H][W])


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
H,W = list(map(int,input().split()))
MAP = [input() for i in range(H)]
  
DP = [[0 for w in range(W)]for h in range(H)]

for w in range(W):
  for h in range(H):
    if h + w == 0:
      if MAP[0][0] == "#":
        DP[0][0] = 1
      continue
    elif h == 0:
      if MAP[h][w-1]+MAP[h][w]==".#": 
        DP[h][w] = DP[h][w-1] +1
      else:
        DP[h][w] = DP[h][w-1]
    elif w == 0:
      if MAP[h-1][w]+MAP[h][w] ==".#": 
        DP[h][w] = DP[h-1][w]+1
      else:
        DP[h][w] = DP[h-1][w]
    else:
      DP[h][w] = min(
        DP[h-1][w] + (1 if MAP[h-1][w]+MAP[h][w] == ".#" else 0),
        DP[h][w-1] + (1 if MAP[h][w-1]+MAP[h][w] == ".#" else 0)
      )

print(DP[-1][-1])

Submission status: Accepted

Solution code:
# i, jまでの#の数
h,w = map(int,input().split())
sl = []
for _ in range(h):
    s = list(input())
    sl.append(s)

dp = [[float("inf") for i in range(w)] for j in range(h)]
if sl[0][0] == ".":
    dp[0][0] = 0
else:
    dp[0][0] = 1

for i in range(h):
    for j in range(w):
        if j != w-1:
            if sl[i][j+1] != sl[i][j]:
                dp[i][j+1] = min(dp[i][j] + 1, dp[i][j+1])
            else:
                dp[i][j + 1] = min(dp[i][j], dp[i][j + 1])
        if i != h-1:
            if sl[i+1][j] != sl[i][j]:
                dp[i+1][j] = min(dp[i][j] + 1, dp[i+1][j])
            else:
                dp[i+1][j] = min(dp[i][j], dp[i+1][j])
def ceil(a, b):
   return a // b + (a % b > 0)

print(ceil(dp[-1][-1],2))

Submission status: Accepted

Solution code:
from collections import deque


def solve(h, w, field):
    s = int(field[0][0] == '#')
    q = deque([(s, s, 0, 0)])
    visited = [[[False] * 2 for _ in range(w)] for _ in range(h)]
    while q:
        cost, state, i, j = q.popleft()
        if visited[i][j][state]:
            continue
        visited[i][j][state] = True
        if i == h - 1 and j == w - 1:
            return cost

        for ni, nj in [(i, j + 1), (i + 1, j)]:
            if ni == h or nj == w:
                continue
            nc = int(field[ni][nj] == '#')
            if state == 0 and nc == 1:
                q.append((cost + 1, nc, ni, nj))
            else:
                q.appendleft((cost, nc, ni, nj))


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

Submission status: Accepted

Solution code:

import numpy as np
from functools import *
import sys
sys.setrecursionlimit(100000)
input = sys.stdin.readline


def acinput():
    return list(map(int, input().split(" ")))




H,W=acinput()

field=[]
dp=np.zeros([H,W])

for i in range(H):
    field.append(list(input()))
    
dp[0,0]=(field[0][0]=="#")

def g(a,b):
    if a=="." and b=="#":
        return 1
    return 0

j=0    
for i in range(1,H):
    dp[i,j]=dp[i-1, j]+g(field[i-1][j],field[i][j])
    
i = 0
for j in range(1,W):
    dp[i, j] = dp[i, j-1]+g(field[i][j-1],field[i][j])

#print(dp)
for i in range(1,H):
    for j in range(1,W):
        l=dp[i,j-1]+g(field[i][j-1],field[i][j])
        u = dp[i-1, j]+g(field[i-1][j], field[i][j])
        dp[i,j]=min(l,u)


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

Submission status: Accepted

Solution code:
h,w=map(int,input().split())
l=[[i for i in input()] for j in range(h)]
INF=float('inf')
dp=[[INF for j in range(w)] for i in range(h)]
dp[0][0]=0
if l[0][0]=="#":
    dp[0][0]+=1
if l[-1][-1]=="#":
    dp[0][0]+=1
for i in range(1,w):
    if l[0][i-1]==l[0][i]:
        dp[0][i]=dp[0][i-1]
    else:
        dp[0][i]=dp[0][i-1]+1
for i in range(1,h):
    for j in range(w):
        if l[i-1][j]==l[i][j]:
            dp[i][j]=dp[i-1][j]
        else:
            dp[i][j]=dp[i-1][j]+1
        if j==0:
            continue
        if l[i][j-1]==l[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[-1][-1]//2)

Submission status: Accepted

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

info = ["." + "x" * (w - 1)] + [input() for i in range(h)]
INF = 10 ** 5
h += 1
dp = [[INF] * w for i in range(h)]
dp[0][0] =  0

for i in range(h):
    for j in range(w):
        for ii, jj in [(i, j + 1), (i + 1, j)] :
            if not(0 <= ii < h and 0 <= jj < w):
                continue
            if info[ii][jj] == "x":
                continue
            if info[i][j] != info[ii][jj] and info[ii][jj] == "#":
                dp[ii][jj] = min(dp[i][j] + 1, dp[ii][jj])
            else:
                dp[ii][jj] = min(dp[i][j], dp[ii][jj])
print(dp[-1][-1])

Submission status: Accepted

Solution code:
from collections import deque
from functools import lru_cache

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

minDist = [[10**10] * W for _ in range(H)]
que = deque([(0, 0, 0 if S[0][0] == '.' else 1, S[0][0] == '.')])

while que:
    h, w, dist, isWhite = que.popleft()

    if minDist[h][w] <= dist:
        continue
    minDist[h][w] = dist

    if h + 1 < H:
        isNextWhite = S[h + 1][w] == '.'
        if isWhite and not isNextWhite:
            que.append((h + 1, w, dist + 1, isNextWhite))
        else:
            que.appendleft((h + 1, w, dist, isNextWhite))
    if w + 1 < W:
        isNextWhite = S[h][w + 1] == '.'
        if isWhite and not isNextWhite:
            que.append((h, w + 1, dist + 1, isNextWhite))
        else:
            que.appendleft((h, w + 1, dist, isNextWhite))

ans = minDist[H - 1][W - 1]
print(ans)

Submission status: Accepted

Solution code:
h,w=map(int,input().split())
s=[]
for i in range(h):
	ss=input()
	s.append(ss)
inf=10**4
dp=[[inf]*w for _ in range(h)]
if s[0][0]=="#":
	dp[0][0]=1
else:
	dp[0][0]=0
for i in range(w-1):
	if s[0][i+1]==".":
		dp[0][i+1]=dp[0][i]
	else:
		dp[0][i+1]=dp[0][i]+1
		if s[0][i]=="#":
			dp[0][i+1]-=1
for i in range(1,h):
	if s[i][0]==".":
		dp[i][0]=dp[i-1][0]
	else:
		dp[i][0]=dp[i-1][0]+1
		if s[i-1][0]=="#":
			dp[i][0]-=1
	for j in range(1,w):
		if s[i][j]==".":
			dp[i][j]=min(dp[i][j-1],dp[i-1][j])
		else:
			p=dp[i][j-1]
			q=dp[i-1][j]
			if s[i][j-1]=="#":
				p-=1
			if s[i-1][j]=="#":
				q-=1
			dp[i][j]=min(p,q)+1
print(dp[-1][-1])

Submission status: Accepted

Solution code:
import numpy as np
h, w = list(map(int, input().split()))
ss = []
for _ in range(h):
    s = input()
    s = s.replace(".", "0").replace("#", "1")
    s = list(map(int, list(s)))
    ss.append(s)
ss = np.array(ss)
    

dp = np.zeros((h, w)).astype(np.int32)
if ss[0,0] == 1:
    dp[0,0] = 1
    

for kh in range(h):
    for kw in range(w):
#         print(kh, kw)
#         print(dp)
        if kh == 0 and kw == 0:
            continue
        if kh == 0:
            a = 9999
        else:
            if ss[kh - 1, kw] == 0 and ss[kh, kw] == 1:
                a = dp[kh - 1, kw] + 1
            else:
                a = dp[kh - 1, kw]

        if kw == 0:
            b = 9999
        else:
            if ss[kh, kw - 1] == 0 and ss[kh, kw] == 1:
                b = dp[kh, kw - 1] + 1
            else:
                b = dp[kh, kw - 1]

        dp[kh, kw] = min([a, b])

print(dp[-1, -1])

Submission status: Accepted

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

inf = 10 ** 18
d = [[inf for _ in range(w)] for _ in range(h)]
d[0][0] = 0

for j in range(1, w):
    if f[0][j] == f[0][j-1]:
        d[0][j] =  d[0][j-1]
    else:
        d[0][j] =  d[0][j-1] + 1

for i in range(1, h):
    if f[i][0] == f[i-1][0]:
        d[i][0] =  d[i-1][0]
    else:
        d[i][0] =  d[i-1][0] + 1

for i in range(1, h):
    for j in range(1, w):
        costi = int(f[i][j] != f[i-1][j])
        costj = int(f[i][j] != f[i][j-1])
        d[i][j] = min(d[i-1][j] + costi, d[i][j-1] + costj)

if f[0][0] == '.':
    print((d[h-1][w-1]+1)//2)
else:
    print(d[h-1][w-1]//2 + 1)

Submission status: Accepted

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

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

for i in range(h):
    for j in range(w):
        if i == j == 0:
            continue
        if i == 0:
            if smap[i][j-1] != smap[i][j]:
                dp[i][j] = dp[i][j-1]+1
            else:
                dp[i][j] = dp[i][j-1]
        elif j == 0:
            if smap[i-1][j] != smap[i][j]:
                dp[i][j] = dp[i-1][j]+1
            else:
                dp[i][j] = dp[i-1][j]
        else:
            up = 0
            if smap[i][j-1] != smap[i][j]:
                up = dp[i][j-1]+1
            else:
                up = dp[i][j-1]
            lp = 0
            if smap[i-1][j] != smap[i][j]:
                lp = dp[i-1][j]+1
            else:
                lp = dp[i-1][j]
            dp[i][j] = min(up, lp)
result = dp[h-1][w-1] // 2
if dp[h-1][w-1] %2 == 1:
    result += 1
if smap[0][0] == '#' and smap[h-1][w-1] == '#':
    result+=1
print(result)

Submission status: Accepted

Solution code:
h,w = map(int,input().split())
raw = [[0 for _ in range(w+1)]]
for _ in range(h):
  tmp = input()
  add = [0]
  for j in range(w):
    if tmp[j] == '.':
      add.append(0)
    else:
      add.append(1)
  raw.append(add)
#for x in raw:
  #print(x)
ans = []
for i in range(1,h+1):
  add = []
  for j in range(1,w+1):
    can = []
    if i == j == 1:
      add.append(raw[1][1])
      continue
    if i != 1:
      if raw[i][j] == 0:
        can.append(ans[i-2][j-1])
      elif raw[i-1][j] == 1:
        can.append(ans[i-2][j-1])
      else:
        can.append(ans[i-2][j-1]+1)
    if j != 1:
      if raw[i][j] == 0:
        can.append(add[j-2])
      elif raw[i][j-1] == 1:
        can.append(add[j-2])
      else:
        can.append(add[j-2]+1)
    add.append(min(can))
  ans.append(add)
#for x in ans:
  #print(x)
print(ans[-1][-1])

Submission status: Accepted

Solution code:
H, W = map(int, input().split())
S = [input() for _ in range(H)]
dp = [[100000]*W for _ in range(H)]
dp[0][0] = int(S[0][0]=="#")
for x in range(1, W):
    dp[0][x] = dp[0][x-1] + (int(S[0][x]=="#") if S[0][x-1]=="." else 0)
for y in range(1, H):
    dp[y][0] = dp[y-1][0] + (int(S[y][0]=="#") if S[y-1][0]=="." else 0)
    for x in range(1, W):
        dp[y][x] = min(
            dp[y][x-1] + (int(S[y][x]=="#") if S[y][x-1]=="." else 0),
            dp[y-1][x] + (int(S[y][x]=="#") if S[y-1][x]=="." else 0)
        )
print(dp[-1][-1])

Submission status: Accepted

Solution code:
h,w=map(int,input().split())
S=[]
for _ in range(h):
    S.append(input())
tbl=[[10**3]*w for _ in range(h)]
if S[0][0]=="#":
    tbl[0][0]=1
else:
    tbl[0][0]=0
for i in range(h):
    for j in range(w):
        if i>=1 and S[i][j]=="#" and S[i-1][j]==".":
            tbl[i][j]=min(tbl[i][j],tbl[i-1][j]+1)
        elif i>=1:
            tbl[i][j]=min(tbl[i][j],tbl[i-1][j])
        if j>=1 and S[i][j]=="#" and S[i][j-1]==".":
            tbl[i][j]=min(tbl[i][j],tbl[i][j-1]+1)
        elif j>=1:
            tbl[i][j]=min(tbl[i][j],tbl[i][j-1])
print(tbl[h-1][w-1])

Submission status: Accepted

Solution code:
import sys
input=sys.stdin.readline
h,w=map(int,input().split())
C=[]
for i in range(h):
    sub_list=input().rstrip()
    C.append(sub_list)
dp=[[0]*w for i in range(h)]
if C[0][0]=='.':
    dp[0][0]=0
else:
    dp[0][0]=1
for i in range(h):
    for j in range(w):
        if i==0 and j==0:
            pass
        else:
            if i==0:
                if C[i][j]=='.':
                    dp[i][j]=dp[i][j-1]
                else:
                    if C[i][j-1]=='.':
                        dp[i][j]=dp[i][j-1]+1
                    else:
                        dp[i][j] = dp[i][j - 1]
            elif j==0:
                if C[i][j]=='.':
                    dp[i][j]=dp[i-1][j]
                else:
                    if C[i-1][j]=='.':
                        dp[i][j]=dp[i-1][j]+1
                    else:
                        dp[i][j] = dp[i-1][j]
            else:
                if C[i][j]=='.':
                    dp[i][j]=min(dp[i][j-1],dp[i-1][j])
                else:
                    if C[i][j-1]=='.':
                        dp[i][j]=dp[i][j-1]+1
                    else:
                        dp[i][j] = dp[i][j - 1]
                    if C[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])
print(dp[h-1][w-1])

Submission status: Accepted

Solution code:
h, w = map(int,input().split())
maero='.'*w
maekai=[999]*w
maekai[0]=0
allkai=[]
for i in range(h):
    root=input()
    nowkai=[]
    for j in range(w):
        if root[j]=='.':
            if j==0:
                nowkai.append(maekai[0])
            else:
                nowkai.append(min(nowkai[-1], maekai[j]))
        else:
            if j==0:
                if maero[j]=='.':
                    nowkai.append(maekai[0]+1)
                else:
                    nowkai.append(maekai[0])
            else:
                if root[j-1]=='.':
                    koho1=nowkai[-1]+1
                else:
                    koho1=nowkai[-1]
                if maero[j]=='.':
                    koho2=maekai[j]+1
                else:
                    koho2=maekai[j]
                #print(koho1, koho2)
                nowkai.append(min(koho1, koho2))
    maero=root
    allkai.append(nowkai)
    maekai=nowkai

#for ak in allkai:
    #print(ak)
print(allkai[-1][-1])

Submission status: Accepted

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

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

def next(h, w):
    ret = []
    if h != H-1:
        ret.append((h+1, w))
    if w != W-1:
        ret.append((h, w+1))

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

for w in range(W-1):
    t = dp[0][w]
    if state[0][w] != state[0][w+1]:
        t += 1
    dp[0][w+1] = t

for h in range(1, H):
    tmp = dp[h-1][0]
    if state[h-1][0] != state[h][0]:
        tmp += 1
    dp[h][0] = tmp
    for w in range(1, W):
        t1 = dp[h][w-1]
        t2 = dp[h-1][w]
        if state[h][w-1] != state[h][w]:
            t1 += 1
        if state[h-1][w] != state[h][w]:
            t2 += 1
        dp[h][w] = min(t1, t2)

p = dp[H-1][W-1]
if p%2 == 0:
    if state[0][0] == ".":
        ans = p//2
    else:
        ans = p//2+1
else:
    ans = (p+1)//2
print(ans)

Submission status: Accepted

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

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

Submission status: Accepted

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

DP = [[0] * W for _ in range(H)]
if s[0][0] == "#":
  DP[0][0] = 1

for i in range(1, W):
  if s[0][i - 1] != s[0][i]:
    DP[0][i] = DP[0][i - 1] + 1
  else:
    DP[0][i] = DP[0][i - 1]

for i in range(1, H):
  DP[i][0] = DP[i - 1][0]
  if s[i][0] != s[i - 1][0]:
    DP[i][0] += 1
  for j in range(1, W):
    x = DP[i][j - 1]
    if s[i][j] != s[i][j - 1]:
      x += 1
    y = DP[i - 1][j]
    if s[i][j] != s[i - 1][j]:
      y += 1
    DP[i][j] = min(x, y)

print((DP[-1][-1] + 1) // 2)

Submission status: Accepted

Solution code:
h, w = map(int, input().split())
s = [input() for _ in range(h)]
d = [[1000000] * w for _ in range(h)]
d[0][0] = 0
for i in range(h):
    for j in range(w):
        if i < h - 1:
            d[i + 1][j] = min(d[i + 1][j], d[i][j] +
                              (1 if s[i][j] != s[i + 1][j] else 0))
        if j < w - 1:
            d[i][j + 1] = min(d[i][j + 1], d[i][j] +
                              (1 if s[i][j] != s[i][j + 1] else 0))
ans = d[h - 1][w - 1]
if s[0][0] == '#':
    ans += 1
if s[h - 1][w - 1] == '#':
    ans += 1
print(ans // 2)

Submission status: Accepted

Solution code:
#list(map(int,input().split()))
n,m=map(int,input().split())
it=[[0 for i in range(m)] for j in range(n)]
for i in range(n):
    j=input()
    for k in range(m):
        if j[k]=="#":
            it[i][k]=0
        else:
            it[i][k]=1
dp=[[0 for i in range(m)] for j in range(n)]
for i in range(n):
    for j in range(m):
        
        if(i>0 or j>0):
            if(i==0):
                dp[i][j]=dp[i][j-1]
                if(it[i][j-1]==1 and it[i][j]==0):
                    dp[i][j]+=1
            elif j==0:
                dp[i][j]=dp[i-1][j]
                if(it[i][j]==0 and it[i-1][j]==1):
                    dp[i][j]+=1
            else:
                a=0
                b=0
                if(it[i][j]==0):
                    if(it[i-1][j]==1):
                        a=1
                    if(it[i][j-1]==1):
                        b=1
                dp[i][j]=min(dp[i-1][j]+a,dp[i][j-1]+b)
        else:
            if it[i][j]==0:
                dp[i][j]=1

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

Submission status: Accepted

Solution code:
h,w=map(int,input().split())
b=[list(input())for _ in range(h)]
ans=[w*[10**9]for _ in range(h)]
ans[0][0]=(b[0][0]=="#")+0
for i in range(h):
  for j in range(w):
    if i==j==0:continue
    if i==0:
      if b[0][j-1]=="." and b[0][j]=="#":ans[0][j]=ans[0][j-1]+1
      else:ans[0][j]=ans[0][j-1]
    elif j==0:
      if b[i-1][0]=="." and b[i][0]=="#":ans[i][0]=ans[i-1][0]+1
      else:ans[i][0]=ans[i-1][0]
    else:
      ii=ans[i-1][j]
      if b[i-1][j]=="." and b[i][j]=="#":ii+=1
      jj=ans[i][j-1]
      if b[i][j-1]=="." and b[i][j]=="#":jj+=1
      ans[i][j]=min(ii,jj)
print(ans[-1][-1])

Submission status: Accepted

Solution code:
import sys
import math
from collections import defaultdict
from bisect import bisect_left, bisect_right

sys.setrecursionlimit(10**7)
def input():
    return sys.stdin.readline()[:-1]

mod = 10**9 + 7

def I(): return int(input())
def LI(): return list(map(int, input().split()))
def LIR(row,col):
    if row <= 0:
        return [[] for _ in range(col)]
    elif col == 1:
        return [I() for _ in range(row)]
    else:
        read_all = [LI() for _ in range(row)]
        return map(list, zip(*read_all))

#################

H,W = LI()
S = [list(map(str, input())) for _ in range(H)]

count = [[0]*W for _ in range(H)]
for i in range(H)[::-1]:
    for j in range(W)[::-1]:
        if i==H-1 and j==W-1:
            if S[i][j] == '#':
                count[i][j] = 1
            else:
                count[i][j] = 0
        elif i==H-1:
            if S[i][j+1]=='.' and S[i][j]=='#':
                count[i][j] = count[i][j+1]+1
            else:
                count[i][j] = count[i][j+1]
        elif j==W-1:
            if S[i+1][j]=='.' and S[i][j]=='#':
                count[i][j] = count[i+1][j]+1
            else:
                count[i][j] = count[i+1][j]
        else:
            if S[i][j+1]=='.' and S[i][j]=='#':
                one = count[i][j+1]+1
            else:
                one = count[i][j+1]
            if S[i+1][j]=='.' and S[i][j]=='#':
                two = count[i+1][j]+1
            else:
                two = count[i+1][j]
            count[i][j] = min(one,two)

print(count[0][0])

Submission status: Accepted

Solution code:
import sys
input=lambda: sys.stdin.readline().rstrip()
h,w=map(int,input().split())
A=[input() for i in range(h)]
n=h*w
edge=[[] for i in range(n)]
for i in range(n):
  h1,w1=i//w,i%w
  if w1!=w-1:
    if A[h1][w1]=="." and A[h1][w1+1]=="#":
      edge[i].append(10**6+i+1)
    else:
      edge[i].append(i+1)
  if h1!=h-1:
    if A[h1][w1]=="." and A[h1+1][w1]=="#":
      edge[i].append(10**6+i+w)
    else:
      edge[i].append(i+w)

import heapq
def dijkstra_heap(s):
  d=[float("inf")]*n
  used=[True]*n
  d[s]=0
  used[s]=False
  edgelist=[]
  for e in edge[s]:
    heapq.heappush(edgelist,e)
  while edgelist:
    minedge=heapq.heappop(edgelist)
    minedge_cost=minedge//(10**6)
    minedge_v=minedge%(10**6)
    if not used[minedge_v]:
      continue
    d[minedge_v] = minedge_cost
    used[minedge_v] = False
    for e in edge[minedge_v]:
      e_cost=e//(10**6)
      e_v=e%(10**6)
      if used[e_v]:
        heapq.heappush(edgelist,e+minedge_cost*10**6)
  return d
D=dijkstra_heap(0)
if A[0][0]=="#":
  print(D[h*w-1]+1)
else:
  print(D[h*w-1])

Submission status: Accepted

Solution code:
import queue

H, W = map(int,input().split())
b = [list(input()) for _ in range(H)]
ini = 0
if b[0][0] == '#':
    ini = 1
dist = [[ini for _ in range(W)] for _ in range(H)]
start = (0,0)
qq = queue.Queue()
for i in range(H):
    for j in range(W):
        tgt = []
        if j==0:
            pass
        else:
            if b[i][j-1] == '.' and b[i][j] == '#':
                tgt.append(dist[i][j-1] + 1)
            else:
                tgt.append(dist[i][j-1])
        if i==0:
            pass
        else:
            if b[i-1][j] == '.' and b[i][j] == '#':
                tgt.append(dist[i-1][j] + 1)
            else:
                tgt.append(dist[i-1][j])
        if i+j==0:
            continue
        dist[i][j] = min(tgt)
print(dist[H-1][W-1])

Submission status: Accepted

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

H,W=map(int,input().split())
MAP=[input().strip() for i in range(H)]

ANS=[[1<<30]*W for i in range(H)]

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

for i in range(H):
    for j in range(W):
        if i+1<H:
            if MAP[i][j]==MAP[i+1][j]:
                ANS[i+1][j]=min(ANS[i+1][j],ANS[i][j])
            else:
                ANS[i+1][j]=min(ANS[i+1][j],ANS[i][j]+1)

        if j+1<W:
            if MAP[i][j]==MAP[i][j+1]:
                ANS[i][j+1]=min(ANS[i][j+1],ANS[i][j])
            else:
                ANS[i][j+1]=min(ANS[i][j+1],ANS[i][j]+1)
            
print((ANS[-1][-1]+1)//2)

Submission status: Accepted

Solution code:
import sys
from collections import deque

def solve():
    input = sys.stdin.readline
    H, W = map(int, input().split())
    S = [input().strip("\n") for _ in range(H)]
    DP = [[100000 for w in range(W)] for _ in range(H)]
    ncol = (0 if S[0][0] == "." else 1)
    q = deque()
    q.append((0, 0, ncol, ncol))
    Se = ((0, 1), (1, 0))
    while q:
        h, w, d, c = q.popleft()
        if d < DP[h][w]:
            DP[h][w] = d
            if c == 0:
                for dh, dw in Se:
                    if h + dh < H and w + dw < W:
                        if S[h+dh][w+dw] == ".": q.append((h+dh, w+dw, d, 0))
                        else: q.append((h+dh, w+dw, d+1, 1))
            else:
                for dh, dw in Se:
                    if h + dh < H and w + dw < W:
                        if S[h+dh][w+dw] == ".": q.append((h+dh, w+dw, d, 0))
                        else: q.append((h+dh, w+dw, d, 1))
    print(DP[H-1][W-1])
    return 0

if __name__ == "__main__":
    solve()