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: Wrong Answer

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

tmp = [input() for _ in range(H)]
S = []
for i in tmp:
    k = []
    for j in i:
        if j == '#':
            k.append(1)
        else:
            k.append(0)
    S.append(k)

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

dp[0][0] = S[0][0]
for i in range(H):
    for j in range(W):
        if j+1 < W:
            dp[i][j+1] = min(dp[i][j+1], dp[i][j]+S[i][j+1])
        if i+1 < H:
            dp[i+1][j] = min(dp[i+1][j], dp[i][j]+S[i+1][j])

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

Submission status: Wrong Answer

Solution code:
h, w = [int(i) for i in input().split()]
A = [input() for i in range(h)]
dp = [[0 for j in range(w)] for i in range(h)]
if A[0][0] == '#':
    dp[0][0] = 1
for j in range(1, w):
    dp[0][j] = dp[0][j-1]
    if A[0][j] == '#':
        dp[0][j] += 1
for i in range(1, h):
    dp[i][0] =  dp[i-1][0]
    if A[i][0] == '#':
        dp[i][0] += 1
for i in range(1, h):
    for j in range(1, w):
        dp[i][j] = min(dp[i-1][j], dp[i][j-1])
        if A[i][j] == '#':
            dp[i][j] += 1
print(dp[-1][-1])

Submission status: Wrong Answer

Solution code:
from collections import deque
# import math


def bfs(maze, mazeColor, h, w, sy, sx, gy, gx):
    for y in range(h):
        for x in range(w):
            maze[y][x] = float("inf")

    if mazeColor[sy][sx] == '.':
        maze[sy][sx] = 0
    else:
        maze[sy][sx] = 1
    que = deque([[sy, sx]])
    while que:
        y, x = que.popleft()
        for i, j in [(1, 0), (0, 1)]:
            nexty, nextx = y + i, x + j
            distColor = mazeColor[nexty][nextx]
            dist = maze[nexty][nextx]
            if distColor != '#':
                if dist > maze[y][x]:
                    maze[nexty][nextx] = maze[y][x] + 0
                    que.append([nexty, nextx])
            else:
                if dist > maze[y][x]:
                    maze[nexty][nextx] = maze[y][x] + 1
                    que.append([nexty, nextx])

    # for i in range(len(maze[0])):
    #    print(maze[i])
    print(maze[gy][gx])


h, w = map(int, input().split())
mazeColor = ['#'+'#'*w+'#']
for i in range(h):
    mazeColor.append('#'+input()+'#')
mazeColor.append('#'+'#'*w+'#')

maze = [[0 for j in range(w+2)] for i in range(h+2)]

bfs(maze, mazeColor, h+1, w+1, 1, 1, h, w)

Submission status: Wrong Answer

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

# process
dp = [[100]*(W+1) for _ in range(H+1)]
dp[0][1] = 0
for i in range(H):
    for j in range(W):
        if S[i][j] == '#':
            dp[i+1][j+1] = min(dp[i+1][j+1], dp[i][j+1]+1, dp[i+1][j]+1)
        else:
            dp[i+1][j+1] = min(dp[i+1][j+1], dp[i][j+1], dp[i+1][j])


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

Submission status: Wrong Answer

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 w in range(1, W):
    if s[0][w] == "#": dp[0][w] += dp[0][w-1] + 1
    else: dp[0][w] += dp[0][w-1]
for h in range(1, H):
    if s[h][0] == "#": dp[h][0] += dp[h-1][0] + 1
    else: dp[h][0] += dp[h-1][0]
for h in range(1, H):
    for w in range(1, W):
        if s[h][w] == "#":
            dp[h][w] += min(dp[h-1][w], dp[h][w-1]) + 1
        else:
            dp[h][w] += min(dp[h-1][w], dp[h][w-1])
print(dp[H-1][W-1])

Submission status: Wrong Answer

Solution code:
H,W=map(int,input().split())
dp=[[0 for i in range(W)] for k in range(H)]
ALL=[]
for i in range(H):
  S=input()
  ALL+=[S]
  for k in range(W):
    if i==0 and k==0:
      if S[k]=="#":
        dp[i][k]=1
      else:
        dp[i][k]=0
    elif i==0:
      if S[k]=="#" and S[k]=="#":
        dp[i][k]=dp[i][k-1]
      elif S[k]=="." and S[k]==".":
        dp[i][k]=dp[i][k-1]
      else:
        dp[i][k]=dp[i][k-1]+1
    elif k==0:
      if S[k]=="#" and S[k]=="#":
        dp[i][k]=dp[i-1][k]
      elif S[k]=="." and S[k]==".":
        dp[i][k]=dp[i-1][k]
      else:
        dp[i][k]=dp[i-1][k]+1
    else:
      if S[k]=="#":
        if S[k-1]=="#" and ALL[i-1][k]=="#":
          dp[i][k]=min(dp[i][k-1],dp[i-1][k])
        elif S[k-1]=="#" and ALL[i-1][k]==".":
          dp[i][k]=min(dp[i][k-1],dp[i-1][k]+1)
        elif S[k-1]=="." and ALL[i-1][k]=="#":
          dp[i][k]=min(dp[i][k-1]+1,dp[i-1][k])
        else:
          dp[i][k]=min(dp[i][k-1],dp[i-1][k])+1
      else:
        if S[k-1]=="#" and ALL[i-1][k]=="#":
          dp[i][k]=min(dp[i][k-1],dp[i-1][k])+1
        elif S[k-1]=="#" and ALL[i-1][k]==".":
          dp[i][k]=min(dp[i][k-1]+1,dp[i-1][k])
        elif S[k-1]=="." and ALL[i-1][k]=="#":
          dp[i][k]=min(dp[i][k-1],dp[i-1][k]+1)
        else:
          dp[i][k]=min(dp[i][k-1],dp[i-1][k])        
ans=dp[H-1][W-1]
print(ans)

Submission status: Wrong Answer

Solution code:
H,W=map(int,input().split())
dp=[[0 for i in range(W)] for k in range(H)]
for i in range(H):
  S=input()
  for k in range(W):
    if i==0 and k==0:
      if S[k]=="#":
        dp[i][k]=1
      else:
        dp[i][k]=0
    elif i==0:
      if S[k]=="#":
        dp[i][k]=dp[i][k-1]+1
      else:
        dp[i][k]=dp[i][k-1]
    elif k==0:
      if S[k]=="#":
        dp[i][k]=dp[i-1][k]+1
      else:
        dp[i][k]=dp[i-1][k]
    else:
      if S[k]=="#":
        dp[i][k]=min(dp[i][k-1],dp[i-1][k])+1
      else:
        dp[i][k]=min(dp[i][k-1],dp[i-1][k])
ans=dp[H-1][W-1]
print(ans)

Submission status: Wrong Answer

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

import queue
q = queue.Queue()
dp = [[0 for _ in range(w)] for _ in range(h)]
q.put([0,0])
closed = [[0,0]]
for i in range(h+w-1):
  jm = i+1 if i < w else w
  if i >= h:
    row = h-1
  else:
    row = i
  js = i - h + 1 if i >= h else 0
  for j in range(js, jm):
    p = [row-j, j]
    if js > 0:
      p = [row-j+js, j]
    if s[p[0]][p[1]] == '#':
      dp[p[0]][p[1]] = 1
    if p[0] > 0 and p[1] > 0:
      if dp[p[0]-1][p[1]] < dp[p[0]][p[1]-1]:
        m = dp[p[0]-1][p[1]]
        if s[p[0]-1][p[1]] == '#':
          dp[p[0]][p[1]] = 0
      else:
        m = dp[p[0]][p[1]-1]
        if s[p[0]][p[1]-1] == '#':
          dp[p[0]][p[1]] = 0
    elif p[0] == 0 and p[1] > 0:
      m = dp[p[0]][p[1]-1]
      if s[p[0]][p[1]-1] == '#':
        dp[p[0]][p[1]] = 0
    else:
      if s[p[0]-1][p[1]] == '#':
        dp[p[0]][p[1]] = 0
      m = dp[p[0]-1][p[1]]
    dp[p[0]][p[1]] += m
print(dp[h-1][w-1])

Submission status: Wrong Answer

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

import queue
q = queue.Queue()
dp = [[0 for _ in range(w)] for _ in range(h)]
q.put([0,0])
closed = [[0,0]]
for i in range(h+w-1):
  jm = i+1 if i < w else w
  if i >= h:
    row = h-1
  else:
    row = i
  js = i - h + 1 if i >= h else 0
  for j in range(js, jm):
    p = [row-j, j]
    if js > 0:
      p = [row-j+js, j]
    if p[0] < h-1 and p[1] < w-1:
      if s[p[0]][p[1]] == '#':
        dp[p[0]][p[1]] = 1
      if p[0] > 0 and p[1] > 0:
        m = min(dp[p[0]-1][p[1]], dp[p[0]][p[1]-1])
      elif p[0] == 0 and p[1] > 0:
        m = dp[p[0]][p[1]-1]
      else:
        m = dp[p[0]-1][p[1]]
    
      dp[p[0]][p[1]] += m
    elif p[1] < w-1:
      if s[p[0]][p[1]] == '#':
        dp[p[0]][p[1]] = 1
      if p[0] > 0 and p[1] > 0:
        m = min(dp[p[0]-1][p[1]], dp[p[0]][p[1]-1])
      elif p[0] == 0 and p[1] > 0:
        m = dp[p[0]][p[1]-1]
      else:
        m = dp[p[0]-1][p[1]]
      dp[p[0]][p[1]] += m
    elif p[0] < h-1:
      if s[p[0]][p[1]] == '#':
        dp[p[0]][p[1]] = 1
      if p[0] > 0 and p[1] > 0:
        m = min(dp[p[0]-1][p[1]], dp[p[0]][p[1]-1])
      elif p[0] == 0 and p[1] > 0:
        m = dp[p[0]][p[1]-1]
      else:
        m = dp[p[0]-1][p[1]]
      dp[p[0]][p[1]] += m
    else:
      if s[p[0]][p[1]] == '#':
        dp[p[0]][p[1]] = 1
      if p[0] > 0 and p[1] > 0:
        m = min(dp[p[0]-1][p[1]], dp[p[0]][p[1]-1])
      elif p[0] == 0 and p[1] > 0:
        m = dp[p[0]][p[1]-1]
      else:
        m = dp[p[0]-1][p[1]]
      dp[p[0]][p[1]] += m
print(dp[h-1][w-1])

Submission status: Wrong Answer

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

dp = [[h*w for i in range(w+1)] for j in range(h+1)]

dp[0][1] = 0
dp[1][0] = 0

for i in range(h):
    for j in range(w):
        print("i", i, "j", j, "s[i][j]", s[i][j])
        print(s[i][j] == '#' and (i == 0 or s[i-1][j] == '.'))
        
        #前の道が（"."またはグリッド外）かつ現在地が#の場合に1を加える
        #前の道が"#"であればまとめて変換できるので何も加えない
        dp[i+1][j+1] = min(
            dp[i][j+1] + (s[i][j] == '#' and (i == 0 or s[i-1][j] == '.')),
            dp[i+1][j] + (s[i][j] == '#' and (j == 0 or s[i][j-1] == '.'))
        )

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

Submission status: Wrong Answer

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

dp = [list(input()) for _ in range(H)]

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

for i in range(W-1):
    dp[0][i+1] += dp[0][i]

for j in range(H-1):
    dp[j+1][0] += dp[j][0]

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

Submission status: Wrong Answer

Solution code:
H,W=list(map(int,input().split()))
l=[list(input()) for i in range(H)]
DP=[[201]*W for i in range(H)]
DP[0][0]=0
for y in range(H):
   for x in range(W):
      if x ==0 and y==0:
         DP[y][x] += 1 if l[y][x] == "#" else 0
         continue
      elif x == 0:
         DP[y][x] = DP[y-1][x]
      elif y == 0:
         DP[y][x] = DP[y][x-1]
      else:
         DP[y][x] = min(DP[y][x-1],DP[y-1][x])
      DP[y][x] += 1 if l[y][x] == "#" else 0
print(DP[H-1][W-1])

Submission status: Wrong Answer

Solution code:
H,W=list(map(int,input().split()))
l=[list(input()) for i in range(H)]
DP=[[201]*W for i in range(H)]
DP[0][0]=0
for y in range(H):
   for x in range(W):
      if x ==0 and y==0:
         DP[y][x] += 1 if l[y][x] == "#" else 0
         continue
      elif x == 0:
         DP[y][x] = DP[y-1][x]
      elif y == 0:
         DP[y][x] = DP[y][x-1]
      else:
         DP[y][x] = min(DP[y][x-1],DP[y-1][x])
      DP[y][x] += 1 if l[y][x] == "#" else 0
print(DP[H-1][W-1])
print(DP)

Submission status: Wrong Answer

Solution code:
from collections import deque
def dfs(x,y,color,ans):
	d=[[0,1],[1,0],[0,-1],[-1,0]]
	c=deque()
	c.append([x,y])
	while c:
		a,b=c.popleft()
		for dx,dy in d:
			aa=a+dx
			ab=b+dy
			if aa>=0 and aa<=h-1 and ab>=0 and ab<=w-1:
				if chk[aa][ab]:
					continue
				if s[aa][ab]==color:
					c.append([aa,ab])
					chk[aa][ab]=True
				else:
					ans.append([aa,ab])
	return
		
h,w=map(int,input().split())
s=[list(input()) for _ in range(h)]
chk=[[False]*w for _ in range(h)]
if s[0][0]=='#':
	cnt=1
	flg='#'
else:
	cnt=0
	flg='.'
ans=deque()
ans.append([0,0])
while ans:
	i,j=ans.popleft()
	chk[i][j]=True
	dfs(i,j,flg,ans)
	if chk[h-1][w-1]:
		print(cnt//2+cnt%2)
		exit()
	else:
		cnt+=1
		if flg=='#':
			flg='.'
		else:
			flg='#'

Submission status: Wrong Answer

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

import queue
q = queue.Queue()
dp = [[0 for _ in range(w)] for _ in range(h)]
q.put([0,0])
closed = [[0,0]]
while not q.empty():
  p = q.get()
  if p[0] < h-1 and p[1] < w-1:
    if s[p[0]][p[1]] == '#':
      dp[p[0]][p[1]] = 1
    if p[0] > 0 and p[1] > 0:
      m = min(dp[p[0]-1][p[1]], dp[p[0]][p[1]-1])
    elif p[0] == 0 and p[1] > 0:
      m = dp[p[0]][p[1]-1]
    else:
      m = dp[p[0]-1][p[1]]
    
    dp[p[0]][p[1]] += m
    if [p[0]+1, p[1]] not in closed:
      q.put([p[0]+1, p[1]])
      closed.append([p[0]+1, p[1]])
    if [p[0], p[1]+1] not in closed:
      q.put([p[0], p[1]+1])
      closed.append([p[0], p[1]+1])
  elif p[1] < w-1:
    if s[p[0]][p[1]] == '#':
      dp[p[0]][p[1]] = 1
    if p[0] > 0 and p[1] > 0:
      m = min(dp[p[0]-1][p[1]], dp[p[0]][p[1]-1])
    elif p[0] == 0 and p[1] > 0:
      m = dp[p[0]][p[1]-1]
    else:
      m = dp[p[0]-1][p[1]]
    dp[p[0]][p[1]] += m
    if [p[0], p[1]+1] not in closed:
      q.put([p[0], p[1]+1])
      closed.append([p[0], p[1]+1])
  elif p[0] < h-1:
    if s[p[0]][p[1]] == '#':
      dp[p[0]][p[1]] = 1
    if p[0] > 0 and p[1] > 0:
      m = min(dp[p[0]-1][p[1]], dp[p[0]][p[1]-1])
    elif p[0] == 0 and p[1] > 0:
      m = dp[p[0]][p[1]-1]
    else:
      m = dp[p[0]-1][p[1]]
    dp[p[0]][p[1]] += m
    if  [p[0]+1, p[1]] not in closed:
      q.put([p[0]+1, p[1]])
      closed.append([p[0]+1, p[1]])
  else:
    if s[p[0]][p[1]] == '#':
      dp[p[0]][p[1]] = 1
    if p[0] > 0 and p[1] > 0:
      m = min(dp[p[0]-1][p[1]], dp[p[0]][p[1]-1])
    elif p[0] == 0 and p[1] > 0:
      m = dp[p[0]][p[1]-1]
    else:
      m = dp[p[0]-1][p[1]]
    dp[p[0]][p[1]] += m
print(dp[h-1][w-1])

Submission status: Wrong Answer

Solution code:
#
# 　　  ⋀_⋀　 
#　　  (･ω･)  
# .／ Ｕ ∽ Ｕ＼
#  │＊　合　＊│
#  │＊　格　＊│ 
#  │＊　祈　＊│ 
#  │＊　願　＊│ 
#  │＊　　　＊│ 
#      ￣
#
import sys
sys.setrecursionlimit(10**6)
input=sys.stdin.readline
from math import floor,sqrt,factorial,hypot,log #log2ないｙｐ
from heapq import heappop, heappush, heappushpop
from collections import Counter,defaultdict,deque
from itertools import accumulate,permutations,combinations,product,combinations_with_replacement
from bisect import bisect_left,bisect_right
from copy import deepcopy
from fractions import gcd
from random import randint
def ceil(a,b): return (a+b-1)//b
inf=float('inf')
mod = 10**9+7
def pprint(*A): 
    for a in A:     print(*a,sep='\n')
def INT_(n): return int(n)-1
def MI(): return map(int,input().split())
def MF(): return map(float, input().split())
def MI_(): return map(INT_,input().split())
def LI(): return list(MI())
def LI_(): return [int(x) - 1 for x in input().split()]
def LF(): return list(MF())
def LIN(n:int): return [I() for _ in range(n)]
def LLIN(n: int): return [LI() for _ in range(n)]
def LLIN_(n: int): return [LI_() for _ in range(n)]
def LLI(): return [list(map(int, l.split() )) for l in input()]
def I(): return int(input())
def F(): return float(input())
def ST(): return input().replace('\n', '')
def main():
    H,W=MI()
    grid = [ST() for _ in range(H)]
    N = H*W
    edge = [[] for _ in range(N)]
    def enc(h,w):
        return h*W+w

    for h in range(H):
        for w in range(W):
            if(h):
                edge[enc(h-1,w)].append((enc(h,w),grid[h][w] == "#"))
            if(w):
                edge[enc(h,w-1)].append((enc(h,w),grid[h][w] == "#"))
    
    q = deque([0])
    dist = [inf]*N
    dist[0] = grid[0][0]=="#"
    while q:
        v = q.popleft()
        for to,cost in edge[v]:
            if(dist[to]!=inf):
                continue
            dist[to] = dist[v] + cost
            if(cost):
                q.append(to)
            else:
                q.appendleft(to)
    print(dist[-1])
if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import collections

def Z(): return int(input())
def ZZ(): return [int(_) for _ in input().split()]

class ver:
    def __init__(self, x, y): self.x, self.y = x, y

def main():
    H, W = ZZ()
    S = [list(input()) for _ in range(H)]
    D = [(1, 0), (-1, 0), (0, 1), (0, -1)]
    check = [[0] * W for _ in range(H)]

    def dfs(i, j, check):
        S[i][j] = '.'
        check[i][j] = 0
        for di, dj in D:
            ni, nj = i+di, j+dj
            if 0 <= ni < H and 0 <= nj < W and check[ni][nj] == 1: check = dfs(ni, nj, check)
        return check

    output = 0
    goal = False
    while True:
        deq = collections.deque()
        check = [[0] * W for _ in range(H)]
        visited = [[0] * W for _ in range(H)]
        if S[0][0] == '.': deq.append(ver(0, 0))
        else: check[0][0] = 1
        while deq:
            v = deq.pop()
            if v.x == H-1 and v.y == W-1:
                goal = True
                break
            for dx, dy in D:
                nx, ny = v.x+dx, v.y+dy
                if 0 <= nx < H and 0 <= ny < W:
                    if S[nx][ny] == '#': check[nx][ny] = 1
                    elif visited[nx][ny] == 0:
                        deq.append(ver(nx, ny))
                        visited[nx][ny] = 1
        if goal: break

        for i in range(H):
            for j in range(W):
                if check[i][j] == 1: check = dfs(i, j, check)
        output += 1
    print(output)
    return

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
H, W = map(int, input().split())
dp = [[H*W for __ in range(W)] for _ in range(H)]
dh = [1, -1, 0, 0]
dw = [0, 0, 1, -1]
S = []
for i in range(H):
    s = input()
    S.append(s)

if (S[0][0] == '#'):
    dp[0][0] = 1
else:
    dp[0][0] = 0


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

        for k in range(4):
            if 0 <= i + dh[k] < H:
                if (S[i + dh[k]][j] == "#"):
                    dp[i + dh[k]][j] = min(dp[i + dh[k]][j], dp[i][j] + 1)
                else:
                    dp[i + dh[k]][j] = min(dp[i + dh[k]][j], dp[i][j])

            if 0 <= j + dw[k] < W:
                if (S[i][j + dw[k]] == "#"):
                    dp[i][j + dw[k]] = min(dp[i][j + dw[k]], dp[i][j] + 1)
                else:
                    dp[i][j + dw[k]] = min(dp[i][j + dw[k]], dp[i][j])


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

Submission status: Wrong Answer

Solution code:
H, W = map(int, input().split())
dp = [[H*W for __ in range(W+5)] for _ in range(H+5)]
S = []
for i in range(H):
    s = input()
    S.append(s)

if (S[0][0] == '#'):
    dp[0][0] = 1
else:
    dp[0][0] = 0


for i in range(H-1):
    for j in range(W-1):
        if(S[i+1][j] == "#"):
            dp[i+1][j] = min(dp[i+1][j], dp[i][j]+1)
        else:
            dp[i+1][j] = min(dp[i+1][j], dp[i][j])

        if (S[i][j+1] == "#"):
            dp[i][j+1] = min(dp[i][j+1], dp[i][j] + 1)
        else:
            dp[i][j+1] = min(dp[i][j+1], dp[i][j])

ans = min(dp[H-1][W-2], dp[H-2][W-1])
if (S[H-1][W-1] == "#"):
    ans += 1
print(ans)

Submission status: Wrong Answer

Solution code:
from heapq import heappush, heappop

def solve(field, H, W):
    
    dir = ((1,0),(0,1))
    INF = float("inf")
    dist = [[INF for j in range(W)] for i in range(H)]

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

    while len(q) != 0:
        prov_cost, h, w = heappop(q)

        if dist[h][w] < prov_cost:
            continue

        for i in range(2):
            n_h = h + dir[i][0]
            n_w = w + dir[i][1]

            if n_h >= H or n_w >= W:
                continue
            
            if field[n_h][n_w] == "#":
                cost = 1
            else:
                cost = 0

            if dist[n_h][n_w] > dist[h][w] + cost:
                dist[n_h][n_w] = dist[h][w] + cost
                heappush(q, (dist[n_h][n_w],n_h,n_w))

    return dist

def main():
    H,W = map(int, input().split())
    field = [[i for i in input()] for j in range(H)]
    ans = solve(field, H, W)

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

if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(1000000)
from collections import deque

def bfs(sx, sy, gx, gy, cnt):
    global flag
    d = [[[0] * (cnt + 1) for i in range(w)] for i in range(h)]
    d[sx][sy][0] = 1
    dx = [1, 0]
    dy = [0, 1]
    que = deque([])
    que.append((sx, sy, 0))
    
    while que:
        p = que.pop()
        if p[0] == gx and p[1] == gy and p[2] <= cnt:
            flag = 1
            return
        
        for i in range(2):
            nx = p[0] + dx[i]
            ny = p[1] + dy[i]
            if 0 <= nx < h and 0 <= ny < w and d[nx][ny][p[2]] != 1:
                if maze[nx][ny] == "#" and p[2] < cnt:
                    que.append((nx, ny, p[2] + 1))
                    d[nx][ny][p[2] + 1] = 1
                elif maze[nx][ny] != "#":
                    que.append((nx, ny, p[2]))
                    d[nx][ny][p[2]] = 1

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

ans = 0
flag = 0

while ans < h * w:
    bfs(0, 0, h-1, w-1, ans)
    if flag == 1:
        break
    ans += 1
    
if maze[0][0] == "#":
    ans += 1
    
print(ans)

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(1000000)

h, w = map(int, input().split())
maze = [list(input()) for i in range(h)]
flag = 0
visited = [[-1] * w for i in range(h)]
    
def dfs(x, y, cnt):
    global flag
    if x == w - 1 and y == h - 1:
        flag = 1
        return 
    
    dx = [1, 0]
    dy = [0, 1]

    for i in range(2):
        nx = x + dx[i]
        ny = y + dy[i]
        
        if 0 <= nx <= w - 1 and 0 <= ny <= h - 1 and visited[ny][nx][cnt] == -1:
            if maze[ny][nx] == ".":
                dfs(nx, ny, cnt)
                visited[ny][nx][cnt] = 1
            elif maze[ny][nx] == "#" and cnt > 0:
                dfs(nx, ny, cnt - 1)
                visited[ny][nx][cnt - 1] = 1

ans = 0

while ans < h * w:
    visited = [[[-1] * (ans + 1) for i in range(w)] for i in range(h)]
    dfs(0, 0, ans)
    if flag == 1:
        break
    ans += 1
    
if maze[0][0] == "#":
    ans += 1
    
print(ans)

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(1000000)

h, w = map(int, input().split())
maze = [list(input()) for i in range(h)]
flag = 0
visited = [[-1] * w for i in range(h)]
    
def dfs(x, y, cnt):
    global flag
    if x == w - 1 and y == h - 1:
        flag = 1
        return 
    
    dx = [1, 0]
    dy = [0, 1]

    for i in range(2):
        nx = x + dx[i]
        ny = y + dy[i]
        
        if 0 <= nx <= w - 1 and 0 <= ny <= h - 1 and visited[ny][nx] == -1:
            if maze[ny][nx] == ".":
                dfs(nx, ny, cnt)
                visited[ny][nx] = 1
            elif maze[ny][nx] == "#" and cnt > 0:
                dfs(nx, ny, cnt - 1)
                visited[ny][nx] = 1

ans = 0

while ans < h * w:
    visited = [[-1] * w for i in range(h)]
    dfs(0, 0, ans)
    if flag == 1:
        break
    ans += 1
    
if maze[0][0] == "#":
    ans += 1
    
print(ans)

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
import sys
# from collections import defaultdict, deque
# from math import sqrt, gcd, factorial, tan, pi, sin, cos
# def input(): return sys.stdin.readline()[:-1] # warning not \n
# def input(): return sys.stdin.buffer.readline()[:-1]


def solve():
    n, m = [int(x) for x in input().split()]
    dp = [[float('inf') for _ in range(m)] for _ in range(n)]
    for i in range(n):
        s = input().strip()
        for j in range(m):
            c = int(s[j] != '.')
            if i == 0 and j == 0:
                dp[i][j] = c
            if i:
                dp[i][j] = min(dp[i][j], dp[i-1][j] + c)
            if j:
                dp[i][j] = min(dp[i][j], dp[i][j-1] + c)

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




t = 1
# t = int(input())
for case in range(1,t+1):
    ans = solve()



"""
1 -> (1, 2) -> (2 ** 3, 3) -> (3, 1)

"""

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
import sys
# from collections import defaultdict, deque
# from math import sqrt, gcd, factorial, tan, pi, sin, cos
def input(): return sys.stdin.readline()[:-1] # warning not \n
# def input(): return sys.stdin.buffer.readline()[:-1]


def solve():
    n, m = [int(x) for x in input().split()]
    dp = [[float('inf') for _ in range(m)] for _ in range(n)]
    for i in range(n):
        s = input().strip()
        for j in range(m):
            c = int(s[j] != '.')
            if i == 0 and j == 0:
                dp[i][j] = c
            if i:
                dp[i][j] = min(dp[i][j], dp[i-1][j] + c)
            if j:
                dp[i][j] = min(dp[i][j], dp[i][j-1] + c)

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




t = 1
# t = int(input())
for case in range(1,t+1):
    ans = solve()



"""
1 -> (1, 2) -> (2 ** 3, 3) -> (3, 1)

"""

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
import sys
# from collections import defaultdict, deque
# from math import sqrt, gcd, factorial, tan, pi, sin, cos
def input(): return sys.stdin.readline()[:-1] # warning not \n
# def input(): return sys.stdin.buffer.readline()[:-1]


def solve():
    n, m = [int(x) for x in input().split()]
    dp = [[float('inf') for _ in range(m)] for _ in range(n)]
    for i in range(n):
        s = input()
        for j in range(m):
            c = int(s[j] != '.')
            if i == 0 and j == 0:
                dp[i][j] = c
            if i:
                dp[i][j] = min(dp[i][j], dp[i-1][j] + c)
            if j:
                dp[i][j] = min(dp[i][j], dp[i][j-1] + c)

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




t = 1
# t = int(input())
for case in range(1,t+1):
    ans = solve()



"""
1 -> (1, 2) -> (2 ** 3, 3) -> (3, 1)

"""

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
import sys
# from collections import defaultdict, deque
# from math import sqrt, gcd, factorial, tan, pi, sin, cos
def input(): return sys.stdin.readline()[:-1] # warning not \n
# def input(): return sys.stdin.buffer.readline()[:-1]


def solve():
    n, m = [int(x) for x in input().split()]
    dp = [[float('inf') for _ in range(m)] for _ in range(n)]
    for i in range(n):
        s = input()
        for j in range(m):
            c = s[j] != '.'
            if i == 0 and j == 0:
                dp[i][j] = int(c)
            if i:
                dp[i][j] = min(dp[i][j], dp[i-1][j] + c)
            if j:
                dp[i][j] = min(dp[i][j], dp[i][j-1] + c)
                
    print(dp[n-1][m-1])
        




t = 1
# t = int(input())
for case in range(1,t+1):
    ans = solve()



"""
1 -> (1, 2) -> (2 ** 3, 3) -> (3, 1)

"""

Submission status: Wrong Answer

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

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

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

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

for j in range(W-1):
    for i in range(H):
        if i <= H - 2:
            dp[i+1][j] = dp[i][j]
            if s[i][j] == '.' and s[i+1][j] == '#':
                dp[i+1][j] += 1
        if j <= W - 2:
            dp[i][j+1] = dp[i][j]
            if s[i][j] == '.' and s[i][j+1] == '#':
                dp[i][j+1] += 1

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

Submission status: Wrong Answer

Solution code:
def getN():
    return int(input())
def getNM():
    return map(int, input().split())
def getList():
    return list(map(int, input().split()))
def getArray(intn):
    return [int(input()) for i in range(intn)]
def input():
    return sys.stdin.readline().rstrip()

from collections import defaultdict, deque, Counter
from sys import exit
import heapq
import math
import fractions
import copy
from itertools import permutations
from operator import mul
from functools import reduce
from bisect import bisect_left, bisect_right

import sys
sys.setrecursionlimit(1000000000)
mod = 10 ** 9 + 7

H, W = getNM()
maze = []
for i in range(H):
    s = input()
    maze.append(list(s))
dp = [[-1] * W for i in range(H)]
dp[0][0] = 0

pos = deque([[0, 0]])
dx = [1, 0]
dy = [0, 1]

ans = 0
while len(pos) > 0:
    x, y = pos.popleft()
    if x == W - 1 and y == H - 1:
        ans = dp[H - 1][W - 1]
    for i in range(2):
        nx = x + dx[i]
        ny = y + dy[i]
        if 0 <= nx < W and 0 <= ny < H and (dp[ny][nx] == -1 or dp[ny][nx] > dp[y][x] + 1):
            if maze[ny][nx] == "#":
                dp[ny][nx] = dp[y][x] + 1
            else:
                dp[ny][nx] = dp[y][x]
            pos.append([nx, ny])
if maze[0][0] == "#":
    print(ans + 1)
else:
    print(ans)

Submission status: Wrong Answer

Solution code:
def getN():
    return int(input())
def getNM():
    return map(int, input().split())
def getList():
    return list(map(int, input().split()))
def getArray(intn):
    return [int(input()) for i in range(intn)]
def input():
    return sys.stdin.readline().rstrip()

from collections import defaultdict, deque, Counter
from sys import exit
import heapq
import math
import fractions
import copy
from itertools import permutations
from operator import mul
from functools import reduce
from bisect import bisect_left, bisect_right

import sys
sys.setrecursionlimit(1000000000)
mod = 10 ** 9 + 7

H, W = getNM()
maze = []
for i in range(H):
    s = input()
    maze.append(list(s))
dp = [[-1] * W for i in range(H)]
dp[0][0] = 0

pos = deque([[0, 0]])
dx = [1, 0]
dy = [0, 1]

ans = 0
while len(pos) > 0:
    x, y = pos.popleft()
    print([x, y])
    if x == W - 1 and y == H - 1:
        ans = dp[H - 1][W - 1]
    for i in range(2):
        nx = x + dx[i]
        ny = y + dy[i]
        if 0 <= nx < W and 0 <= ny < H and (dp[ny][nx] == -1 or dp[ny][nx] > dp[y][x]):
            if maze[ny][nx] == "#":
                dp[ny][nx] = dp[y][x] + 1
            else:
                dp[ny][nx] = dp[y][x]
            pos.append([nx, ny])
if maze[0][0] == "#":
    print(ans + 1)
else:
    print(ans)

Submission status: Wrong Answer

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

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

def search(i,j,count):
    global ans

    if counter[i][j]!=999:
        ans=min(ans,count+counter[i][j])
        return(counter[i][j])

    dist=999

    if i==H-1 and j==W-1:
        ans=min(ans,count)
        return 0

    if j<W-1:
        if S[i][j]=="." and S[i][j+1]=="#":
            count+=1
        dist=search(i,j+1,count) + (S[i][j]=="." and S[i][j+1]=="#")
    if i<H-1:
        if S[i][j]=="." and S[i+1][j]=="#":
            count+=1
        dist=min(dist,search(i+1,j,count)+(S[i][j]=="." and S[i+1][j]=="#"))
    
    counter[i][j]=dist
    return dist
search(0,0,(S[0][0]=="#")*1)
print(ans)