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: Runtime Error

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

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

for i in range(1,W):
  if s[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 j == 0:
      if s[i][j] == '.':
        dp[i][j] = dp[i-1][j]
      else:
        dp[i][j] = dp[i-1][j]+1
    else:
      if s[i][j] == '.':
        dp[i][j] = min(dp[i-1][j],dp[i][j-1])
      else:
        left = 0
        up = 0
        if s[i-1][j] == '.':
          left = 1
        if s[i][j-1] == '.':
          up = 1
        dp[i][j] = min(dp[i-1][j]+left,dp[i][j-1]+up)
print(dp[-1][-1])

Submission status: Runtime Error

Solution code:
from collections import *
H,W=map(int,input().split())
S=[input() for i in range(H)]
count=0
stack=deque([[0,0,0,S[0][0]=="#"]])
RuiW=[[0] for i in range(H)]
RuiH=[[0] for i in range(W)]
if S[0][0]=="#":
    RuiW[0][0]=1
    RuiH[0][0]=1

for h in range(H):
    flag=0
    for w in range(1,W):
        RuiW[h].append(RuiW[h][-1]+bool(S[h][w]=="#" and S[h][w-1]=="."))
for w in range(W):
    for h in range(1,H):
        RuiH[w].append(RuiH[w][-1]+bool(S[h][w]=="#" and S[h-1][w]=="."))

Range=range(1,100)
idle_max=10**9
visited=[[idle_max for i in range(W)] for m in range(H)]
#print(RuiW)
#print(RuiH)
while stack:
    h,w,m,Flag=stack.popleft()
    if visited[h][m]<m:
        continue
    for i in Range:
        if h+i>=H:
            break
        M=RuiH[w][h+i]-(RuiH[w][h]-RuiH[w][h]%2)+m

        if visited[h+i][w]>M:
            visited[h+i][w]=M
            stack.append([h+i,w,M,0])
    for i in Range:
        if w+i>=W:
            break
        M=RuiW[h][w+i]-(RuiW[h][w]-RuiW[h][w]%2)+m
        if visited[h][w+i]>M:
            visited[h][w+i]=M
            stack.append([h,w+i,M,0])
#print(visited)
print(visited[-1][-1])

Submission status: Runtime Error

Solution code:
def SearchPoint(sw, sh, coun):  #現在地から空白地帯までの距離を出す
    if sw == w-1 and sh == h-1: return w-1,h-1,2
    dist1 ,dist2= 1000,1000
    rx1,rx2,ry1,ry2= 0,0,0,0
    if sw < w-1:
        rx1, ry1, dist1 = serE(sw, sh, coun)
    if sh < h-1:
        rx2, ry2, dist2 = serS(sw, sh, coun)
    if dist1 <= dist2:
        return rx1, ry1, dist1
    else:
        return rx2, ry2, dist2

def serE(ssw, ssh, cou):
    if a[ssw + 1][ssh] == '.':
        return ssw + 1, ssh, cou + 1
    else:
        return SearchPoint(ssw+1,ssh,cou+1)

def serS(ssw, ssh, cou):
    if a[ssw][ssh + 1] == '.':
        return ssw, ssh + 1, cou + 1
    else:
        return SearchPoint(ssw, ssh + 1, cou + 1)
        
w, h = map(int, input().split())
a = [input() for i in range(h)]
count = 0

if a[0][0] == '#':
    count += 1
    a[0] = "." + str(a[1:])

nx ,ny ,co= 0,0,0

while 1:
    if nx == w - 1 and ny == h - 1:
        break
    nx, ny, co = SearchPoint(nx, ny, 0)
    #print(str(nx)+" " + str(ny))
    if nx == ny == 0: break
    if co > 1:
        count +=1

print(count)

Submission status: Runtime Error

Solution code:
def SearchPoint(sw, sh, coun):  #現在地から空白地帯までの距離を出す
    if sw == w-1 and sh == h-1: return w-1,h-1,2
    dist1 ,dist2= 1000,1000
    rx1,rx2,ry1,ry2= 0,0,0,0
    if sw < w-1:
        rx1, ry1, dist1 = serE(sw, sh, coun)
    if sh < h-1:
        rx2, ry2, dist2 = serS(sw, sh, coun)
    if dist1 <= dist2:
        return rx1, ry1, dist1
    else:
        return rx2, ry2, dist2

def serE(ssw, ssh, cou):
    if a[ssw + 1][ssh] == '.':
        return ssw + 1, ssh, cou + 1
    else:
        return SearchPoint(ssw+1,ssh,cou+1)

def serS(ssw, ssh, cou):
    if a[ssw][ssh + 1] == '.':
        return ssw, ssh + 1, cou + 1
    else:
        return SearchPoint(ssw, ssh + 1, cou + 1)
        
w, h = map(int, input().split())
a = [input() for i in range(h)]
count = 0

if a[0][0] == '#':
    count += 1
    a[0] = "." + str(a[1:])

nx ,ny ,co= 0,0,0

while 1:
    if nx == w - 1 and ny == h - 1:
        break
    nx, ny, co = SearchPoint(nx, ny, 0)
    print(str(nx)+" " + str(ny))
    if nx == ny == 0: break
    if co > 1:
        count +=1

print(count)

Submission status: Runtime Error

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

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

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

Submission status: Runtime Error

Solution code:
from heapq import heappush,heappop,heapify
from collections import deque,defaultdict,Counter
from itertools import permutations,combinations,groupby
import sys,bisect,string,math,time,functools,random
def Golf():*a,=map(int,open(0))
def I():return int(input())
def S_():return input()
def IS():return input().split()
def LS():return [i for i in input().split()]
def LI():return [int(i) for i in input().split()]
def LI_():return [int(i)-1 for i in input().split()]
def NI(n):return [int(input()) for i in range(n)]
def NI_(n):return [int(input())-1 for i in range(n)]
def StoLI():return [ord(i)-97 for i in input()]
def ItoS(n):return chr(n+97)
def LtoS(ls):return ''.join([chr(i+97) for i in ls])
def GI(V,E,Directed=False,index=0):
    org_inp=[];g=[[] for i in range(n)]
    for i in range(E):
        inp=LI();org_inp.append(inp)
        if index==0:inp[0]-=1;inp[1]-=1
        if len(inp)==2:
            a,b=inp;g[a].append(b)
            if not Directed:g[b].append(a)
        elif len(inp)==3:
            a,b,c=inp;aa=(inp[0],inp[2]);bb=(inp[1],inp[2]);g[a].append(bb)
            if not Directed:g[b].append(aa)
    return g,org_inp
def GGI(h,w,search=[],replacement_of_found='.',mp_def={'#':1,'.':0}):
#h,w,g,sg=GGI(h,w,search=['S','G'],replacement_of_found='.',mp_def={'#':1,'.':0}) # sample usage
    mp=[1]*(w+2);found={}
    for i in range(h):
        s=input()
        for char in search:
            if char in s:
                found[char]=((i+1)*(w+2)+s.index(char)+1)
                mp_def[char]=mp_def[replacement_of_found]
        mp+=[1]+[mp_def[j] for j in s]+[1]
    mp+=[1]*(w+2)
    return h+2,w+2,mp,found
def TI(n):return GI(n,n-1)
def bit_combination(k,n=2):return [[tb//(n**bt)%n for bt in range(k)] for tb in range(n**k)]
def show(*inp,end='\n'):
    if show_flg:print(*inp,end=end)

YN=['YES','NO'];Yn=['Yes','No']
mo=10**9+7
inf=float('inf')
l_alp=string.ascii_lowercase
#sys.setrecursionlimit(10**7)
input=lambda: sys.stdin.readline().rstrip()

def ran_input():
    n=random.randint(4,16)
    rmin,rmax=1,10
    a=[random.randint(rmin,rmax) for _ in range(n)]
    return n,a

show_flg=False
show_flg=True

h,w=LI()
h,w,g,sg=GGI(h,w)
dp=[1e6]*(h*w)
dp[w+1]=g[w+1]

for j in range(h*w-w):
  for d in (1,w):
    dp[j+d]=min(dp[j]+(g[j],g[j+d])==(0,1),dp[j+d])

print(dp[(h-2)*w+w-2])

Submission status: Runtime Error

Solution code:
import math

N = int(input())
A = list(map(int,input()))
B = []
M = math.ceil(math.log(N,2)) 

for i in range(N):
  a = 0
  for j in range(1,M+1,1):
    a += math.floor((N-1)/(2**j))-math.floor((i)/(2**j))-math.floor((N-1-i)/(2**j))
  if a == 0:
    B.append(1)
  else:
    B.append(0)
b = 0
for i in range(N):
  b += B[i]*A[i]
if b % 2 == 1:
  print(1)
else:
  for i in range(N):
    if A[i] == 2:
      print(0)
      break
  else:
    c = 0
    for i in range(N):
      A[i] = (A[1]-1)//2
      c += B[i]*A[i]
    if c % 2 == 1:
      print(2)
    else:
      print(0)

Submission status: Runtime Error

Solution code:
import math

N = int(input())
A = list(map(int,input()))
B = []
M = math.ceil(math.log(N,2)) 

for i in range(N):
  a = 0
  for j in range(1,M+1,1):
    a += math.floor((N-1)/(2**j))-math.floor((i)/(2**j))-math.floor((N-1-i)/(2**j))
  if a == 0:
    B.append(1)
  else:
    B.append(0)
    
b = 0
for i in range(N):
  b += B[i]*A[i]
if b % 2 == 1:
  print(1)
else:
  for i in range(N):
    if A[i] == 2:
      print(0)
      break
  else:
    for i in range(N):
      A[i] = (A[1]-1)//2
    for i in range(N):
      a = 0
      C = []
      for j in range(1,M+1,1):
        a += math.floor((N-1)/(2**j))-math.floor((i)/(2**j))-math.floor((N-1-i)/(2**j))
      if a == 0:
        C.append(1)
      else:
        C.append(0)
    
    for i in range(N):
      b += C[i]*A[i]
    if b % 2 == 1:
      print(2)
    else:
      print(0)

Submission status: Runtime Error

Solution code:
maxw = 100
bw = 1
MAXX = (maxw+1)*(maxw+1)
weight = []


w, h = map(int, raw_input().split(" "))
wei = []
wwei = [MAXX] * (w+2)
wei.append(wwei)
weight.append([MAXX] * (w+2))
for i in range(h):
    wwei = [MAXX]*(w+2)
    weight.append([MAXX] * (w+2))
    gr = raw_input().rstrip("\r\n")
    for j, c in enumerate(gr):
        if c == ".":
            wwei[j+1] = 0
        else:
            wwei[j+1] = bw
    wei.append(wwei)

wwei = [MAXX] * (w+2)
wei.append(wwei)
weight.append([MAXX] * (w+1))

def calcWB(ww, hh):
    for i in range(1, hh+1):
        for j in range(1, ww+1):
            zz = weight[i][j] + wei[i][j+1]
            yy = weight[i][j] + wei[i+1][j]
            if weight[i][j+1] > zz:
                weight[i][j + 1] = zz
            if weight[i+1][j] > yy:
                weight[i+1][j] = yy

def calcW(ww, hh):
    if (ww == 0) and (hh == 0):
        return wei[ww][hh]

    if (ww < 0) or (hh < 0):
        return MAXX

    wLeft = calcW(ww-1, hh)
    wUp = calcW(ww, hh-1)
    return wei[ww][hh] + min(wLeft, wUp)

#weiz = calcW(w-1, h-1)

weight[1][1] = wei[1][1]
calcWB(w, h)
weiz = weight[w][h]
out = int(weiz)

print(str(out)+"\n")

Submission status: Runtime Error

Solution code:
maxw = 100
bw = 1
MAXX = (maxw+1)*(maxw+1)
weight = []


w, h = map(int, raw_input().split(" "))
wei = []
wwei = [MAXX] * (w+2)
wei.append(wwei)
weight.append([MAXX] * (w+2))
for i in range(h):
    wwei = [MAXX]*(w+2)
    weight.append([MAXX] * (w+2))
    gr = raw_input().rstrip("\r\n")
    for j, c in enumerate(gr):
        if c == ".":
            wwei[j+1] = 0
        else:
            wwei[j+1] = bw
    wei.append(wwei)

wwei = [MAXX] * (w+2)
wei.append(wwei)
weight.append([MAXX] * (w+1))

def calcWB(ww, hh):
    for i in range(1, hh+1):
        for j in range(1, ww+1):
            zz = weight[i][j] + wei[i][j+1]
            yy = weight[i][j] + wei[i+1][j]
            if weight[i][j+1] > zz:
                weight[i][j + 1] = zz
            if weight[i+1][j] > yy:
                weight[i+1][j] = yy

def calcW(ww, hh):
    if (ww == 0) and (hh == 0):
        return wei[ww][hh]

    if (ww < 0) or (hh < 0):
        return MAXX

    wLeft = calcW(ww-1, hh)
    wUp = calcW(ww, hh-1)
    return wei[ww][hh] + min(wLeft, wUp)

#weiz = calcW(w-1, h-1)

weight[1][1] = wei[1][1]
calcWB(w, h)
weiz = weight[w][h]
out = int(weiz/200)

print(str(out)+"\n")

Submission status: Runtime Error

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 j in range(max(W, H)):
            if 0<=i-j<min(W, H):
                if j==0:
                    if s[j][i-j-1]=='.' and s[j][i-j]=='#':
                        ans[j][i-j] = ans[j][i-j-1] + 1
                    else:
                        ans[j][i-j] = ans[j][i-j-1]
                elif i-j==0:
                    if s[j-1][i-j]=='.' and s[j][i-j]=='#':
                        ans[j][i-j] = ans[j-1][i-j] + 1
                    else:
                        ans[j][i-j] = ans[j-1][i-j]
                else:
                    if (s[j-1][i-j]=='.' or s[j][i-j-1]=='.') and s[j][i-j]=='#':
                        ans[j][i-j] = min(ans[j-1][i-j], ans[j][i-j-1]) + 1
                    else:
                        ans[j][i-j] = min(ans[j-1][i-j], ans[j][i-j-1])
    # print(ans)
    print(ans[-1][-1])

if __name__ == '__main__':
    resolve()

Submission status: Runtime Error

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


当初の解法は、Breath First Searchを使おうとしていた
回答はDPだった
WALL = '#'
stack = [(0, 0, 0)]
min_cnt = H * W

# BFSのアレンジ
while stack:
    y, x, cnt = stack.pop()

    if S[y][x] == WALL:
        cnt += 1

    if (y, x) == (H - 1, W - 1):
        # 0回を見つけたら強制終了
        if cnt == 0:
            min_cnt = 0
            break
        # それ以外は継続
        else:
            min_cnt = cnt

    next_y = y + 1
    next_x = x + 1

    # 打ち切りを入れる
    if min_cnt and min_cnt <= cnt:
        pass
    else:
        if next_y < H and next_x < W:
            # WALLじゃない方を優先して、listの後ろへ入れる
            if S[y][next_x] != WALL and S[next_y][x] == WALL:
                stack.append([next_y, x, cnt])
                stack.append([y, next_x, cnt])
            elif S[y][next_x] == WALL and S[next_y][x] != WALL:
                stack.append([y, next_x, cnt])
                stack.append([next_y, x, cnt])
            # 両方WALLの場合
            elif S[y][next_x] == WALL and S[next_y][x] == WALL:
                # もとの最後方を優先する
                if stack:
                    tmp_y, tmp_x, tmp_cnt = stack.pop()
                    stack.append([y, next_x, cnt])
                    stack.append([next_y, x, cnt])
                    stack.append([tmp_y, tmp_x, tmp_cnt])
                else:
                    stack.append([y, next_x, cnt])
                    stack.append([next_y, x, cnt])
            else:
                stack.append([next_y, x, cnt])
                stack.append([y, next_x, cnt])
        elif next_y == H and next_x < W:
            stack.append([y, next_x, cnt])
        elif next_y < H and next_x == W:
            stack.append([next_y, x, cnt])

print(min_cnt)


# h, w = map(int,input().split())
# S = [input() for i in range(h)]
# 
# A = [[0] * w for i in range(h)]
# 
# A[0][0] = 0 if S[0][0] == "." else 1
# 
# for i in range(1, w):
#     if S[0][i-1] == "." and S[0][i] == "#":
#         A[0][i] = A[0][i-1] + 1
#     else:
#         A[0][i] = A[0][i-1]
# 
# for i in range(1, h):
#     if S[i-1][0] == "." and S[i][0] == "#":
#         A[i][0] = A[i-1][0] + 1
#     else:
#         A[i][0] = A[i-1][0]
# 
# for i in range(1, h):
#     for j in range(1, w):
#         a = A[i-1][j]
#         if S[i-1][j] == "." and S[i][j] == "#":
#             a += 1
#         b = A[i][j-1]
#         if S[i][j-1] == "." and S[i][j] == "#":
#             b += 1
#         A[i][j] = min(a, b)
# # print(A)
# print(A[-1][-1])

Submission status: Runtime Error

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):
        for j in range(max(W, H)):
            if 0<=i-j<min(W, H):
                if j==0:
                    if s[j][i-j-1]=='.' and s[j][i-j]=='#':
                        ans[j][i-j] = ans[j][i-j-1] + 1
                    else:
                        ans[j][i-j] = ans[j][i-j-1]
                elif i-j==0:
                    if s[j-1][i-j]=='.' and s[j][i-j]=='#':
                        ans[j][i-j] = ans[j-1][i-j] + 1
                    else:
                        ans[j][i-j] = ans[j-1][i-j]
                else:
                    if (s[j-1][i-j]=='.' or s[j][i-j-1]=='.') and s[j][i-j]=='#':
                        ans[j][i-j] = min(ans[j-1][i-j], ans[j][i-j-1]) + 1
                    else:
                        ans[j][i-j] = min(ans[j-1][i-j], ans[j][i-j-1])
    # print(ans)
    print(ans[-1][-1])

if __name__ == '__main__':
    resolve()

Submission status: Runtime Error

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

S = [input() for _ in range(W)]

M=[]

def dfs(m,n, history):
    history_ = history + S[m][n]
    if H - m >1:
        dfs(m+1,n, history_)
        
    if W-n >1:
        dfs(m,n+1, history_)
        
    if H-m ==1 and H-n ==1:
        count = 0
        for h in history_:
            if h == '#':
                count +=1
        M.append(count)
        
    return 
        
    
dfs(0,0, '')
print(min(M))

Submission status: Runtime Error

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

for i in range(1,w):
    if s[i][0]=="#" and s[i-1][0]==".":
        d[i][0]=d[i-1][j]+1
    else:
        d[i][0]=d[i-1][0]

for i in range(1,w):
    for j in range(1,h):
        if s[i][j]=="#" and s[i][j-1]==".":
            p=d[i][j-1]+1
        else:
            p=d[i][j-1]
        if s[i][j]=="#" and s[i-1][j]==".":
            q=d[i-1][j]+1
        else:
            q=d[i-1][j]
        d[i][j]=min(p,q)
# for i in d:
#     print(i)
print(d[-1][-1])

Submission status: Runtime Error

Solution code:

maxw = 100
bw = maxw*2
MAXX = (maxw+1)*(maxw+1)
weight = []


h, w = map(int, raw_input().split(" "))
wei = []
wwei = [MAXX] * (w+2)
wei.append(wwei)
weight.append([MAXX] * (w+2))
for i in range(h):
    wwei = [MAXX]*(w+2)
    weight.append([MAXX] * (w+2))
    gr = raw_input().rstrip("\r\n")
    for j, c in enumerate(gr):
        if c == ".":
            wwei[j+1] = 1
        else:
            wwei[j+1] = bw
    wei.append(wwei)

wwei = [MAXX] * (w+2)
wei.append(wwei)
weight.append([MAXX] * (w+1))

def calcWB(ww, hh):
    for i in range(1, hh+1):
        for j in range(1, ww+1):
            zz = weight[i][j] + wei[i][j+1]
            yy = weight[i][j] + wei[i+1][j]
            if weight[i][j+1] > zz:
                weight[i][j + 1] = zz
            if weight[i+1][j] > yy:
                weight[i+1][j] = yy

def calcW(ww, hh):
    if (ww == 0) and (hh == 0):
        return wei[ww][hh]

    if (ww < 0) or (hh < 0):
        return MAXX

    wLeft = calcW(ww-1, hh)
    wUp = calcW(ww, hh-1)
    return wei[ww][hh] + min(wLeft, wUp)

#weiz = calcW(w-1, h-1)

weight[1][1] = wei[1][1]
calcWB(w, h)
weiz = weight[w][h]
out = int(weiz/200)

print(str(out)+"\n")

Submission status: Runtime Error

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

grid_state = []

# 1 = black, 0 = white

for _ in range(w):
    temp = [int(s) for s in input().replace(".", "0").replace("#", "1")]
    grid_state.append(temp)

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

grid_cost[0][0] = grid_state[0][0]

for i in range(1, h + w - 1):
    j = i
    if j > w - 1:
        j = w - 1
    while((j >= 0) and (i - j < h)):
        if i - j == 0:
            if grid_state[i - j][j - 1] == 1:
                grid_cost[i - j][j] = grid_cost[i - j][j - 1]
            else:
                grid_cost[i - j][j] = grid_cost[i - j][j - 1] + grid_state[i - j][j]
        elif j == 0:
            if grid_state[i - j - 1][j] == 1:
                grid_cost[i - j][j] = grid_cost[i - j - 1][j]
            else:
                grid_cost[i - j][j] = grid_cost[i - j - 1][j] + grid_state[i - j][j]
        else:
            min_cost = min([grid_cost[i - j - 1][j], grid_cost[i - j][j - 1]])

            if grid_state[i - j][j] == 0:
                grid_cost[i - j][j] = min([grid_cost[i - j - 1][j], grid_cost[i - j][j - 1]])
            elif (grid_state[i - j - 1][j] == 1) and (grid_cost[i - j - 1][j] <= grid_cost[i - j][j - 1]):
                grid_cost[i - j][j] = min_cost
            elif (grid_state[i - j - 1][j] == 0) and (grid_cost[i - j - 1][j] < grid_cost[i - j][j - 1]):
                grid_cost[i - j][j] = min_cost + 1
            elif (grid_state[i - j][j - 1] == 1) and (grid_cost[i - j - 1][j] >= grid_cost[i - j][j - 1]):
                grid_cost[i - j][j] = min_cost
            else:
                grid_cost[i - j][j] = min_cost + 1

        j -= 1

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

Submission status: Runtime Error

Solution code:
h,w=map(int,input().split())
s=[list(input()) for i in range(w)]
inf = h*w
d=[[inf]*h for i in range(w)]
if s[0][0]=="#":
    d[0][0]=1
else:
    d[0][0]=0
if w>1:
    for j in range(1,w):
        if s[0][j]=="#" and s[0][j-1]==".":
            d[0][j]=d[0][j-1]+1
        else:
            d[0][j]=d[0][j-1]
if h>1:
    for i in range(1,h):
        if s[i][0]=="#" and s[i-1][0]==".":
            d[i][0]=d[i-1][j]+1
        else:
            d[i][0]=d[i-1][0]
if h>1 and w>1:
    for i in range(1,h):
        for j in range(1,w):
            if s[i][j]=="#" and s[i][j-1]==".":
                p=d[i][j-1]+1
            else:
                p=d[i][j-1]
            if s[i][j]=="#" and s[i-1][j]==".":
                q=d[i-1][j]+1
            else:
                q=d[i-1][j]
            d[i][j]=min(p,q)
# for i in d:
#     print(i)
print(d[-1][-1])

Submission status: Runtime Error

Solution code:
from heapq import heappush,heappop,heapify
from collections import deque,defaultdict,Counter
from itertools import permutations,combinations,groupby
import sys,bisect,string,math,time,functools,random
def Golf():*a,=map(int,open(0))
def I():return int(input())
def S_():return input()
def IS():return input().split()
def LS():return [i for i in input().split()]
def LI():return [int(i) for i in input().split()]
def LI_():return [int(i)-1 for i in input().split()]
def NI(n):return [int(input()) for i in range(n)]
def NI_(n):return [int(input())-1 for i in range(n)]
def StoLI():return [ord(i)-97 for i in input()]
def ItoS(n):return chr(n+97)
def LtoS(ls):return ''.join([chr(i+97) for i in ls])
def GI(V,E,Directed=False,index=0):
    org_inp=[];g=[[] for i in range(n)]
    for i in range(E):
        inp=LI();org_inp.append(inp)
        if index==0:inp[0]-=1;inp[1]-=1
        if len(inp)==2:
            a,b=inp;g[a].append(b)
            if not Directed:g[b].append(a)
        elif len(inp)==3:
            a,b,c=inp;aa=(inp[0],inp[2]);bb=(inp[1],inp[2]);g[a].append(bb)
            if not Directed:g[b].append(aa)
    return g,org_inp
def GGI(h,w,search=None,replacement_of_found='.',mp_def={'#':1,'.':0}):
#h,w,g,sg=GGI(h,w,search=['S','G'],replacement_of_found='.',mp_def={'#':1,'.':0}) # sample usage
    mp=[1]*(w+2);found={}
    for i in range(h):
        s=input()
        for char in search:
            if char in s:
                found[char]=((i+1)*(w+2)+s.index(char)+1)
                mp_def[char]=mp_def[replacement_of_found]
        mp+=[1]+[mp_def[j] for j in s]+[1]
    mp+=[1]*(w+2)
    return h+2,w+2,mp,found
def TI(n):return GI(n,n-1)
def bit_combination(k,n=2):return [[tb//(n**bt)%n for bt in range(k)] for tb in range(n**k)]
def show(*inp,end='\n'):
    if show_flg:print(*inp,end=end)

YN=['YES','NO'];Yn=['Yes','No']
mo=10**9+7
inf=float('inf')
l_alp=string.ascii_lowercase
#sys.setrecursionlimit(10**7)
input=lambda: sys.stdin.readline().rstrip()

def ran_input():
    n=random.randint(4,16)
    rmin,rmax=1,10
    a=[random.randint(rmin,rmax) for _ in range(n)]
    return n,a

show_flg=False
show_flg=True

h,w=LI()
h,w,g,sg=GGI(h,w)
dp=[inf]*(h*w)
dp[w+1]=g[w+1]

for j in range(h*w-w):
  for d in (1,w):
    dp[j+d]=min(dp[j]+1 if (g[j],g[j+d])==(0,1) else dp[j],dp[j+d])

print(dp[(h-2)*w+w-2])

Submission status: Runtime Error

Solution code:
black = 1
count = 0
flag = False
def check(board, now):
    global flag, count
    if now[0] > len(board) -2 or board[now[0]+1][now[1]]==black:
        if now[1] > len(board[0]) -2 or board[now[0]][now[1]+1]==black:
            if flag == False:
                count += 1
                flag = True
            if now[1] < len(board[0]) -1:
                return [now[0], now[1]+1]
            elif now[0] < len(board) -1:
                return [now[0]+1, now[1]]
        else:
            flag = False
            return [now[0], now[1]+1]
    else:
        flag = False
        return [now[0]+1, now[1]]
def main():
    global count, flag
    H, W = map(int, input().split())
    board = [[white for i in range(W)] for j in range(H)]
    for i in range(H):
        s = input()
        for j in range(W):
            if s[j] == ".":
                board[i][j] = white
            else:
                board[i][j] = black
    if board[0][0] == black:
        count += 1
        flag = True
    now = [0, 0]
    while now != [H-1, W-1]:
        now = check(board, now)
    print(count)
if __name__ == "__main__":
    main()

Submission status: Runtime Error

Solution code:
from heapq import heappush,heappop,heapify
from collections import deque,defaultdict,Counter
from itertools import permutations,combinations,groupby
import sys,bisect,string,math,time,functools,random
def Golf():*a,=map(int,open(0))
def I():return int(input())
def S_():return input()
def IS():return input().split()
def LS():return [i for i in input().split()]
def LI():return [int(i) for i in input().split()]
def LI_():return [int(i)-1 for i in input().split()]
def NI(n):return [int(input()) for i in range(n)]
def NI_(n):return [int(input())-1 for i in range(n)]
def StoLI():return [ord(i)-97 for i in input()]
def ItoS(n):return chr(n+97)
def LtoS(ls):return ''.join([chr(i+97) for i in ls])
def GI(V,E,Directed=False,index=0):
    org_inp=[];g=[[] for i in range(n)]
    for i in range(E):
        inp=LI();org_inp.append(inp)
        if index==0:inp[0]-=1;inp[1]-=1
        if len(inp)==2:
            a,b=inp;g[a].append(b)
            if not Directed:g[b].append(a)
        elif len(inp)==3:
            a,b,c=inp;aa=(inp[0],inp[2]);bb=(inp[1],inp[2]);g[a].append(bb)
            if not Directed:g[b].append(aa)
    return g,org_inp
def GGI(h,w,search=None,replacement_of_found='.',mp_def={'#':1,'.':0}):
#h,w,g,sg=GGI(h,w,search=['S','G'],replacement_of_found='.',mp_def={'#':1,'.':0}) # sample usage
    mp=[1]*(w+2);found={}
    for i in range(h):
        s=input()
        for char in search:
            if char in s:
                found[char]=((i+1)*(w+2)+s.index(char)+1)
                mp_def[char]=mp_def[replacement_of_found]
        mp+=[1]+[mp_def[j] for j in s]+[1]
    mp+=[1]*(w+2)
    return h+2,w+2,mp,found
def TI(n):return GI(n,n-1)
def bit_combination(k,n=2):return [[tb//(n**bt)%n for bt in range(k)] for tb in range(n**k)]
def show(*inp,end='\n'):
    if show_flg:print(*inp,end=end)

YN=['YES','NO'];Yn=['Yes','No']
mo=10**9+7
inf=float('inf')
l_alp=string.ascii_lowercase
#sys.setrecursionlimit(10**7)
input=lambda: sys.stdin.readline().rstrip()

def ran_input():
    n=random.randint(4,16)
    rmin,rmax=1,10
    a=[random.randint(rmin,rmax) for _ in range(n)]
    return n,a

show_flg=False
show_flg=True

h,w=LI()
h,w,g,_=GGI(h,w)
dp=[inf]*(h*w)
dp[w+1]=g[w+1]

for j in range(h*w-w):
  for d in (1,w):
    dp[j+d]=min(dp[j]+1 if (g[j],g[j+d])==(0,1) else dp[j],dp[j+d])

print(dp[(h-2)*w+w-2])

Submission status: Runtime Error

Solution code:
h,w=map(int,input().split())
s=[list(input()) for i in range(w)]
inf = h*w
d=[[inf]*h for i in range(w)]
if s[0][0]=="#":
    d[0][0]=1
else:
    d[0][0]=0
# def tate(x,y):
#     if x==0:
#         return d[x][y]
#     if s[x-1][y]=="#":
#         return tate(x-1,y)
#     return d[x-1][y]
# def yoko(x,y):
#     if y==0:
#         return d[x][y]
#     if s[x][y-1]=="#":
#         return yoko(x,y-1)
#     return d[x][y-1]
for j in range(1,w):
    if s[0][j]=="#" and s[0][j-1]==".":
        d[0][j]=d[0][j-1]+1
    else:
        d[0][j]=d[0][j-1]
for i in range(1,h):
    if s[i][0]=="#" and s[i-1][0]==".":
        d[i][0]=d[i-1][j]+1
    else:
        d[i][0]=d[i-1][0]
for i in range(1,h):
    for j in range(1,w):
        if s[i][j]=="#" and s[i][j-1]==".":
            p=d[i][j-1]+1
        else:
            p=d[i][j-1]
        if s[i][j]=="#" and s[i-1][j]==".":
            q=d[i-1][j]+1
        else:
            q=d[i-1][j]
        d[i][j]=min(p,q)
# for i in d:
#     print(i)
print(d[-1][-1])