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())
S = [input() for _ in range(H)]

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

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

for i in range(1, W):
    if S[0][i] == '#':
        dp[0][i] = dp[0][i-1] + 1
    else:
        dp[0][i] = dp[0][i-1]

for j in range(1, H):
    if S[j][0] == '#':
        dp[j][0] = dp[j-1][0] + 1
    else:
        dp[j][0] = dp[j-1][0]

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

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

Submission status: Wrong Answer

Solution code:
# 新しいvalueのほうが小さい場合のみ設定
def set_val(map, x, y, value):
    key = str(x) + " " + str(y)
    if key in map:
        if value < map[key]:
            map[key] = value
    else:
        map[key] = value
    return map


size_x, size_y = map(int, input().split())
count = size_x + size_y
temp_values = []

for i in range(size_x):
    temp_values.append(input())

values = []
for value in temp_values:
    values.append(list(value))

initial = 0
yet = True
all_black = True
if values[0][0] == "#":
    initial = 1

check_value = {"0 0": initial}
# 探索処理
for i in range(count):
    check_temp_value = {}
    for key in check_value.keys():
        x, y = map(int, key.split())
        value = check_value.get(key)
        # 下に移動
        if x + 1 <= size_x - 1:
            if values[x + 1][y] == "#" and values[x][y] == ".":
                # 異なる経路で同一座標に到達した場合、小さいほうの値を設定
                check_temp_value = set_val(check_temp_value, x + 1, y, value + 1)
                yet = False
                all_black = False
            else:
                check_temp_value = set_val(check_temp_value, x + 1, y, value)
        # 右に移動
        if y + 1 <= size_y - 1:
            if values[x][y + 1] == "#" and values[x][y] == ".":
                # 異なる経路で同一座標に到達した場合、小さいほうの値を設定
                check_temp_value = set_val(check_temp_value, x, y + 1, value + 1)
                yet = False
                all_black = False
            else:
                check_temp_value = set_val(check_temp_value, x, y + 1, value)
    check_value = check_temp_value
    if len(check_value) == 1:
        # ゴールについたら終了
        break
    yet = True

# すべて黒なら無条件に1
if all_black:
    print(1)

# 最後が#なら加算
result_val_add = 0
if values[size_x - 1][size_y - 1] == "#" and yet :
    result_val_add = 1
print(list(check_value.values())[0] + result_val_add)

Submission status: Wrong Answer

Solution code:
# 新しいvalueのほうが小さい場合のみ設定
def set_val(map, x, y, value):
    key = str(x) + " " + str(y)
    if key in map:
        if value < map[key]:
            map[key] = value
    else:
        map[key] = value
    return map


size_x, size_y = map(int, input().split())
count = size_x + size_y
temp_values = []

for i in range(size_x):
    temp_values.append(input())

values = []
for value in temp_values:
    values.append(list(value))

initial = 0
yet = True
if values[0][0] == "#":
    initial = 1

check_value = {"0 0": initial}
# 探索処理
for i in range(count):
    check_temp_value = {}
    for key in check_value.keys():
        x, y = map(int, key.split())
        value = check_value.get(key)
        # 下に移動
        if x + 1 <= size_x - 1:
            if values[x + 1][y] == "#" and values[x][y] == ".":
                # 異なる経路で同一座標に到達した場合、小さいほうの値を設定
                check_temp_value = set_val(check_temp_value, x + 1, y, value + 1)
                yet = False
            else:
                check_temp_value = set_val(check_temp_value, x + 1, y, value)
        # 右に移動
        if y + 1 <= size_y - 1:
            if values[x][y + 1] == "#" and values[x][y] == ".":
                # 異なる経路で同一座標に到達した場合、小さいほうの値を設定
                check_temp_value = set_val(check_temp_value, x, y + 1, value + 1)
                yet = False
            else:
                check_temp_value = set_val(check_temp_value, x, y + 1, value)
    check_value = check_temp_value
    if len(check_value) == 1:
        # ゴールについたら終了
        break
    yet = True

# 最後が#なら加算
result_val_add = 0
if values[size_x - 1][size_y - 1] == "#" and yet:
    result_val_add = 1
print(list(check_value.values())[0] + result_val_add)

Submission status: Wrong Answer

Solution code:
h,w=map(int,input().split())
s=[list(input()) for i in range(h)]
inf = h*w
d=[[inf]*w for i in range(h)]
if s[0][0]=="#":
    d[0][0]=1
else:
    d[0][0]=0
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])

Submission status: Wrong Answer

Solution code:
white = 0
black = 1
count = 0
flag = False
def check(board, now):
    global flag, count, white, black
    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, white, black
    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: Wrong Answer

Solution code:
#!/usr/bin/env python3
import sys


def solve(H: int, W: int, s: "List[str]"):

    class Variable(object):
        def __init__(self, H, W, s):
            self.deepest = 0
            self.deepest_loc = [0, 0]
            self.replaced_loc = []
            self.H = H
            self.W = W
            self.s = s

        def start_is_black(self):
            #スタートが#なら，置き換え発生
            if self.s[0][0] == "#":
                self.replaced_loc.append([0, 0])
                self.s[0][0] = "."

        def goal_is_black(self):
            #ゴールが#なら，置き換え発生
            if self.s[H - 1][W - 1] == "#":
                self.replaced_loc.append([H - 1, W - 1])
                self.s[H - 1][W - 1] = "."

    def dfs_first(h, w):
        if h + w == H + W - 2:
            return True
        elif s[h][w] == ".":

            tmp = v.deepest
            v.deepest = max(v.deepest, h + w)
            if v.deepest != tmp:
                v.deepest_loc = [h, w]

            if h + 1 < H:
                if dfs_first(h + 1, w):
                    return True
            if w + 1 < W:
                if dfs_first(h, w + 1):
                    return True

        return False

    def dfs(h, w):
        if h == 0 and w == 0:
            v.start_is_black()

        if h + w == H + W - 2:
            # 自身がゴールなら，終了
            v.goal_is_black()
            return True

        elif v.s[h][w] == ".":

            tmp = v.deepest
            v.deepest = max(v.deepest, h + w)
            if v.deepest != tmp:
                v.deepest_loc = [h, w]

            if v.deepest == h + w and v.deepest_loc == [h, w]:
                # 最深部からの探索

                if h + w + 1 == H + W - 2:
                    # 隣がゴールなら終了
                    v.goal_is_black()
                    return True

                def dfs_replaced(replaced_h, replaced_w):
                    # 隣接壁を置き換えながら進む
                    # ゴールできないと，置き換えを消去
                    v.s[replaced_h][replaced_w] = "."
                    v.replaced_loc.append([replaced_h, replaced_w])

                    if dfs(replaced_h, replaced_w):
                        return True
                    else:
                        v.s[replaced_h][replaced_w] = "#"
                        v.replaced_loc.remove([replaced_h, replaced_w])
                    
                if h + 1 < H:
                    if v.s[h + 1][w] == ".":
                        if dfs(h + 1, w):
                            return True
                    else:
                        if dfs_replaced(h + 1, w):
                            return True

                if w + 1 < W:
                    if v.s[h][w + 1] == ".":
                        if dfs(h, w + 1):
                            return True
                    else:
                        if dfs_replaced(h, w + 1):
                            return True

        return False

    def count_switch(pair):
        count = 1
        for i in range(len(pair) - 1):
            dh = abs(pair[i][0] - pair[i + 1][0])
            dw = abs(pair[i][1] - pair[i + 1][1])
            if dh + dw == 1 and dh * dw == 0:
                pass
            else:
                count += 1
        return count

    v = Variable(H, W, s)

    if dfs_first(0, 0):
        print(0)
    else:
        if dfs(v.deepest_loc[0], v.deepest_loc[1]):
            print(count_switch(v.replaced_loc))
        else:
            print("ERROR:not arrived")


# Generated by 1.1.6 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()

    H, W = map(int, input().split())
    s = [list(str(input())) for h in range(H)]


    solve(H, W, s)

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
# Author: cr4zjh0bp
# Created: Fri Mar 20 22:48:43 UTC 2020
import sys
 
stdin = sys.stdin
inf = 1 << 60
mod = 1000000007
 
ni      = lambda: int(ns())
nin     = lambda y: [ni() for _ in range(y)]
na      = lambda: list(map(int, stdin.readline().split()))
nan     = lambda y: [na() for _ in range(y)]
nf      = lambda: float(ns())
nfn     = lambda y: [nf() for _ in range(y)]
nfa     = lambda: list(map(float, stdin.readline().split()))
nfan    = lambda y: [nfa() for _ in range(y)]
ns      = lambda: stdin.readline().rstrip()
nsn     = lambda y: [ns() for _ in range(y)]
ncl     = lambda y: [list(ns()) for _ in range(y)]
nas     = lambda: stdin.readline().split()

from collections import deque

h, w = na()
m = nsn(h)

def bfs():
    q = deque()
    al = 0
    f = False
    if m[0][0] == '#':
        al += 1
        f = True
    q.append((0, 0, al, f))
    d = [[inf] * w for _ in range(h)]
    res = inf
    dx, dy = [0, 1], [1, 0]
    while len(q):
        p = q.popleft()
        x, y, l, flag = p
        for i in range(2):
            nx, ny = x + dx[i], y + dy[i]
            if nx >= 0 and nx < w and ny >= 0 and ny < h and d[ny][nx] > l:
                if m[y][x] == '#':
                    if not flag:
                        l += 1
                    q.append((nx, ny, l, True))
                else:
                    q.append((nx, ny, l, False))
                d[ny][nx] = l
    return d[h - 1][w - 1]

print(bfs())

Submission status: Wrong Answer

Solution code:
# Author: cr4zjh0bp
# Created: Fri Mar 20 22:48:43 UTC 2020
import sys
 
stdin = sys.stdin
inf = 1 << 60
mod = 1000000007
 
ni      = lambda: int(ns())
nin     = lambda y: [ni() for _ in range(y)]
na      = lambda: list(map(int, stdin.readline().split()))
nan     = lambda y: [na() for _ in range(y)]
nf      = lambda: float(ns())
nfn     = lambda y: [nf() for _ in range(y)]
nfa     = lambda: list(map(float, stdin.readline().split()))
nfan    = lambda y: [nfa() for _ in range(y)]
ns      = lambda: stdin.readline().rstrip()
nsn     = lambda y: [ns() for _ in range(y)]
ncl     = lambda y: [list(ns()) for _ in range(y)]
nas     = lambda: stdin.readline().split()

from collections import deque

h, w = na()
m = nsn(h)

def bfs():
    q = deque()
    al = 0
    if m[0][0] == '#':
        al += 1
    q.append((0, 0, al, False))
    d = [[inf] * w for _ in range(h)]
    res = inf
    dx, dy = [0, 1], [1, 0]
    while len(q):
        p = q.popleft()
        x, y, l, flag = p
        for i in range(2):
            nx, ny = x + dx[i], y + dy[i]
            if nx >= 0 and nx < w and ny >= 0 and ny < h and d[ny][nx] > l:
                if m[y][x] == '#':
                    if not flag:
                        l += 1
                    q.append((nx, ny, l, True))
                else:
                    q.append((nx, ny, l, False))
                d[ny][nx] = l
    return d[h - 1][w - 1]

print(bfs())

Submission status: Wrong Answer

Solution code:
from collections import defaultdict
import queue

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

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

n = 0
for i in range(H-1):
    if c[i][0] == "." and c[i+1][0] == "#":
        n += 1
    dp[i+1][0] = n
m = 0
for i in range(W-1):
    if c[0][i] == "." and c[0][i+1] == "#":
        m += 1
    dp[0][i+1] = m

for i in range(1, H):
    for g in range(1, W):
        if c[i-1][g] == "." and c[i][g] == "#":
            dp[i][g] = min(dp[i-1][g]+1, dp[i][g])
        else:
            dp[i][g] = min(dp[i-1][g], dp[i][g])

        if c[i][g-1] == "." and c[i][g] == "#":
            dp[i][g] = min(dp[i][g-1]+1, dp[i][g])
        else:
            dp[i][g] = min(dp[i][g-1], dp[i][g])

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

Submission status: Wrong Answer

Solution code:
white = 0
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
    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
    now = [0, 0]
    while now != [H-1, W-1]:
        now = check(board, now)
    print(count)
if __name__ == "__main__":
    main()

Submission status: Wrong Answer

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

T = [0] * H * W

k = 0

if S[k] == '#':
    T[k] = 1
else:
    T[k] = 0

U = [False] * H * W
U[k] = True

v = T[k]
R = {k:v}

def get_search_address(add):
    p = []
    x = add % W
    y = add // W
    next_x = x+1
    next_y = y+1
    if next_x <= (W-1):
        p.append(W*y+next_x)
    if next_y <= (H-1):
        p.append(W*next_y+x)
    next_x = x-1
    next_y = y-1
    if 0 <= next_x:
        p.append(W*y+next_x)
    if 0 <= next_y:
        p.append(W*next_y+x)
    return p

while True:
    # print('k:{}'.format(k))
    # print('R:{}'.format(R))
    p = get_search_address(k)
    # print('p:{}'.format(p))
    for n in p:
        # print('n:{}'.format(n))
        if S[n] == '#':
            # print('#')
            if not U[n]:
                # print('test1')
                T[n] = T[k]+1
                R[n] = T[n]
                U[n] = True
            else:
                # print('test2')
                if T[n] > T[k]+1:
                    # print('test3')
                    T[n] = T[k]+1
                    R[n] = T[n]
        else:
            # print('.')
            if not U[n]:
                # print('test4')
                T[n] = T[k]
                R[n] = T[n]
                U[n] = True
            else:
                # print('test5')
                if T[n] > T[k]:
                    # print('test6')
                    T[n] = T[k]
                    R[n] = T[n]

    # print('T:{}'.format(T))
    del R[k]
    if not R:
        break
    k = min(R, key=R.get)

print(T[H*W-1])

Submission status: Wrong Answer

Solution code:
h, w = map(int, input().split())
ans = []
for i in range(h):
    ans.append([9999999999] * w)
arr = []
for i in range(h):
    s = list(input())
    arr.append(s)
if arr[0][0] == '#': ans[0][0] = 1
else: ans[0][0] = 0
for i in range(h):
    for j in range(w):
        if i == 0 and j == 0: continue
        if j - 1 >= 0: 
            ans[i][j] = min(ans[i][j], ans[i][j - 1])
        if i - 1 >= 0: ans[i][j] = min(ans[i][j], ans[i - 1][j])
        if arr[i][j] == '#':
            chh = 0
            temp = ans[i][j]
            if j - 1 >= 0:
                if temp == ans[i][j - 1]:
                    if arr[i][j - 1] == '.':
                        ans[i][j] -= -1
                        chh = 1
            if i - 1 >= 0:
                if temp == ans[i - 1][j]:
                    if chh == 1: 
                        if arr[i - 1][j] == '#': ans[i][j] += -1
                    elif arr[i - 1][j] == '.':
                        ans[i][j] -= -1
print(ans[h - 1][w - 1])

Submission status: Wrong Answer

Solution code:
H, W = map(int, input().split())
S=[['' for i in range(W)] for j in range(H)]
for i in range(H):
  S[i]=list(input())
index=[[0 for i in range(W)] for j in range(H)]
#if S[0][0]=="#":
#  count+=1
#  S[0][0]="."
#if S[H-1][W-1]=="#":
#  count+=1
#  S[H-1][W-1]="."
for i in range(H):
  for j in range(W):
    if i==0:
      upIndex=1000
    else:
      upIndex=index[i-1][j]
    if j==0:
      leftIndex=1000
    else:
      leftIndex=index[i][j-1]
    if i==0 and j==0:
      if S[i][j]=="#":
        index[i][j]=1
      else:
        index[i][j]=0
    else:
      if leftIndex<upIndex:
        if S[i][j]!=leftIndex and S[i][j]=="#":
          index[i][j]=leftIndex+1
        else:
          index[i][j]=leftIndex
      else:
        if S[i][j]!=upIndex and S[i][j]=="#":
          index[i][j]=upIndex+1
        else:
          index[i][j]=upIndex

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

Submission status: Wrong Answer

Solution code:
h, w = map(int, input().split())
ans = []
for i in range(h):
    ans.append([9999999999] * w)
arr = []
for i in range(h):
    s = list(input())
    arr.append(s)
if arr[0][0] == '#': ans[0][0] = 1
else: ans[0][0] = 0
for i in range(h):
    for j in range(w):
        if i == 0 and j == 0: continue
        if j - 1 >= 0: 
            ans[i][j] = min(ans[i][j], ans[i][j - 1])
        if i - 1 >= 0: ans[i][j] = min(ans[i][j], ans[i - 1][j])
        if arr[i][j] == '#':
            chh = 0
            temp = ans[i][j]
            if j - 1 >= 0:
                if ans[i][j] == ans[i][j - 1]:
                    if arr[i][j - 1] == '.':
                        ans[i][j] -= -1
                        chh = 1
            if i - 1 >= 0:
                if temp == ans[i - 1][j]:
                    if chh == 1: 
                        if arr[i - 1][j] == '#': ans[i][j] += -1
                    elif arr[i - 1][j] == '.':
                        ans[i][j] -= -1
print(ans[h - 1][w - 1])

Submission status: Wrong Answer

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,search=['S','G'],replacement_of_found='.',mp_def={'#':1,'.':0})
dp=[1e6]*(h*w)
dp[h+1]=g[h+1]

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

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

Submission status: Wrong Answer

Solution code:
#!usr/bin/env python3
from collections import defaultdict, deque
from heapq import heappush, heappop
from itertools import permutations, accumulate
import sys
import math
import bisect
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def I(): return int(sys.stdin.readline())
def LS():return [list(x) for x in sys.stdin.readline().split()]
def S():
    res = list(sys.stdin.readline())
    if res[-1] == "\n":
        return res[:-1]
    return res
def IR(n):
    return [I() for i in range(n)]
def LIR(n):
    return [LI() for i in range(n)]
def SR(n):
    return [S() for i in range(n)]
def LSR(n):
    return [LS() for i in range(n)]

sys.setrecursionlimit(1000000)
mod = 1000000007

d = [(1,0),(0,1)]
def solve():
    h,w = LI()
    s = [input() for i in range(h)]
    bfs = [[-1]*w for i in range(h)]
    bfs[0][0] = 1&(s[0][0] == "#")
    q = deque([(0,0)])
    while q:
        y,x = q.popleft()
        if (y,x) == (h-1,w-1):
            print(bfs[y][x])
            return
        b = bfs[y][x]
        for dy,dx in d:
            ny,nx = y+dy,x+dx
            if 0 <= ny < h and 0 <= nx < w:
                if bfs[ny][nx] < 0:
                    if s[ny][nx] == "#" and s[y][x] != "#":
                        nb = b+1
                        q.append((ny,nx))
                    else:
                        nb = b
                        q.appendleft((ny,nx))
                    bfs[ny][nx] = nb
    return

#Solve
if __name__ == "__main__":
    solve()

Submission status: Wrong Answer

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,search=['S','G'],replacement_of_found='.',mp_def={'#':1,'.':0})
dp=[10**6]*(h*w)
dp[h+1]=g[h+1]

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

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

Submission status: Wrong Answer

Solution code:
from collections import deque
h, w = map(int, input().split())
S = [input() for _ in range(h)]
stack = deque()
seen = [[False]*w for _ in range(h)]
stack.append((int(S[0][0]=="#"), 0, 0))
seen[0][0] = True
while stack:
  cnt, y, x = stack.pop()
  if y==h-1 and x==w-1:
    print(cnt)
    break
  if y+1<h:
    if not seen[y+1][x]:
      seen[y+1][x] = True
      if S[y+1][x] == "#" and S[y][x] == ".":
        stack.appendleft((cnt+1, y+1, x))
      else:
        stack.append((cnt, y+1, x))
  if x+1 < w:
    if not seen[y][x+1]:
      seen[y][x+1] = True
      if S[y][x+1] == "#" and S[y][x] == ".":
        stack.appendleft((cnt+1, y, x+1))
      else:
        stack.append((cnt, y, x+1))

Submission status: Wrong Answer

Solution code:
from collections import deque

h, w = map(int, input().split())
S = [[int(c == '.') for c in input()] for _ in range(h)]
dp = [[h+w]*w for _ in range(h)]
dp[0][0] = int(S[0][0] == 0)

queue = [deque() for i in range(h+w+1)]
queue[int(S[0][0] == 0)].append((0, 0))
def bfs(val):
    while queue[val]:
        x, y = queue[val].popleft()
        for dx, dy in [(1,0), (0,1), (-1,0), (0,-1)]:
            if x+dx not in (-1, w) and y+dy not in (-1, h):
                if S[y+dy][x+dx]:
                    if val < dp[y+dy][x+dx]:
                        dp[y+dy][x+dx] = val
                        queue[val].append((x+dx, y+dy))    
                else:
                    if val+1 < dp[y+dy][x+dx]:
                        dp[y+dy][x+dx] = val+1
                        queue[val+1].append((x+dx, y+dy))
        if val+1 < h+w:
            bfs(val+1)
            
bfs(int(S[0][0] == 0))
print(dp[h-1][w-1])