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: Time Limit Exceeded

Solution code:
import sys
from collections import deque
input = sys.stdin.readline

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

s = []

for _ in range(H):
    s.append(input().strip())

r = 0
c = 0
if s[0][0] == '#':
    cost = 1
else:
    cost = 0
now = deque()
now.append([r,c, cost])

while True:
    cur = now.popleft()
    r = cur[0]
    c = cur[1]
    cost = cur[2]
    if r == H-1 and c == W-1:
        break
    if c < W-1 and s[r][c + 1] == '.':
        now.appendleft([r,c+1,cost])
    if r < H-1 and s[r + 1][c] == '.':
        now.appendleft([r+1,c,cost])
    flag = False
    if c < W-1 and s[r][c + 1] == '#':
        now.append([r,c+1,cost+1])
    if r < H-1 and s[r + 1][c] == '#':
        now.append([r+1,c,cost+1])
print(cost)

Submission status: Time Limit Exceeded

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

def dfs(row, col, count):
    global n, m
    global grid

    if row == n-1 and col == m-1:
        if grid[row][col] == '.':
            count += 1
        dp[row][col] = max(dp[row][col], count)
        return
    else:
        if grid[row][col] == '.':
            count += 1
        dp[row][col] = max(dp[row][col], count)
        if row+1 <= n-1:
            dfs(row+1,col,count)
        if col+1 <= m-1:
            dfs(row,col+1,count)


n, m = map(int, input().split())
counts = [0]
dp = [[0 for i in range(m)]for j in range(n)]
grid = [[0 for i in range(m)]for j in range(n)]
for row in range(n):
    temp = input()
    for col in range(m):
        grid[row][col] = temp[col]

dfs(0,0,0)
print(m+n-1 - dp[n-1][m-1])

Submission status: Time Limit Exceeded

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

def g(m):
  if data[0][0] == '.':
    a = 0
  else:
    a = 1
    
  for i in range(1,m,1):
    if data[0][i] == '.':
      continue
    elif data[0][i] == '#' and data[0][i-1] == '.':
      a += 1
    else:
      continue
  return a

def h(n):
  if data[0][0] == '.':
    a = 0
  else:
    a = 1
    
  for i in range(1,n,1):
    if data[i][0] == '.':
      continue
    elif data[i][0] == '#' and data[i-1][0] == '.':
      a += 1
    else:
      continue
  return a
  
def f(n,m):
  if n == 1:
    return g(m)
  elif m == 1:
    return h(n)
  else:
    if data[n-1][m-1] == '.':
      return min(f(n-1,m),f(n,m-1))
    elif data[n-2][m-1] == '.':
      if data[n-1][m-2] == '.':
        return min(f(n-1,m)+1,f(n,m-1)+1)
      else:
        return min(f(n-1,m)+1,f(n,m-1))
    else:
      if data[n-1][m-2] == '.':
        return min(f(n-1,m),f(n,m-1)+1)
      else:
        return min(f(n-1,m),f(n,m-1))
      
print(f(H,W))

Submission status: Time Limit Exceeded

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

count = [float('inf')]
def dfs(x,y,cnt):
    if x==H-1 and y==W-1:
        if count[0] > cnt:
            count[0] = cnt
        return
    if y < W-1:
        if field[x][y]=='#':
            cnt += 1
        dfs(x,y+1,cnt)
    if x < H-1:
        if field[x][y]=='#':
            cnt += 1
        dfs(x+1,y,cnt)


if field[0][0]=='#':
    dfs(0,0,1)
else:
    dfs(0,0,0)

print(count[0])

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

h,w = map(int,input().split())
F = [input() for _ in range(h)]
direct = [[0,1],[1,0]]
que = deque()
que.append([0,0])
INF = 10**5
dp = [[INF]*w for _ in range(h)]


dp[0][0] = 0

while len(que)>0:  
  x,y = que.pop()    
  for dy,dx in direct:    
    ny = y+dy
    nx = x+dx
    if (0 <= nx < w) and (0 <= ny < h):
      if F[ny][nx] == F[y][x]:        
        if dp[ny][nx] >= dp[y][x]:
          dp[ny][nx] = dp[y][x]
          que.append([ny,nx])
      else:        
        if dp[ny][nx] >= dp[y][x] + 1 :        
          dp[ny][nx] = dp[y][x] + 1          
          que.append([ny,nx])   

ans = (dp[-1][-1]+1)//2
if F[0][0] == '#':
  ans += 1
print(ans)

Submission status: Time Limit Exceeded

Solution code:

def main():



    from collections import deque


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

    q = deque()

    if a[0][0]=='.':
        q.appendleft((0,0,0))
    else:
        q.appendleft((0,0,1))

    while(True):
        f = q.popleft()
        x, y, c = f[0], f[1], f[2]
        for u, v in [(1,0), (0,1)]:
            if x + u <= w - 1 and y + v<= h - 1:
                if x+u == w-1 and y+v == h-1:
                    n = a[w-1][h-1]=='#'
                    print(c+n)
                    exit()

                n = a[x+u][y+v]=='.'
                if n:
                    q.appendleft((x + u, y + v, c + 0))
                else:
                    q.append((x + u, y + v, c + 1))



if __name__=='__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
from queue import Queue

H,W = map(int,input().split())
S = [list(input()) for _ in range(H)]
#%%
q = Queue()

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

dx = [0,1]
dy = [1,0]
c = 0
f = 0
if S[0][0]=='#':
    c = 1
    f = 1
q.put([c,f,0,0])
while not(q.empty()):
    c,f,x,y = q.get()
    for i in range(2):
        nc = c
        nx = x+dx[i]
        ny = y+dy[i]
        if nx>=H or ny>=W:
            continue
        
        if f==0 and (S[nx][ny]=='#'):
            nc = c+1
        
        if nc < dist[nx][ny]: 
            dist[nx][ny] = nc
            nf = S[nx][ny]=='#'
            q.put([nc,nf,nx,ny])
        
print(dist[H-1][W-1])

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
H, W = map(int, input().split())
m = [list(input()) for i in range(0, H)]
counts = [[-1] * W for i in range(0, H)]   
si, sj = 0, 0
if m[si][sj] == '#':
    counts[si][sj] = 1
else:
    counts[si][sj] = 0
q = deque([[si, sj]])
while q:
    i, j = q.popleft()
    for movei, movej in [[1, 0], [0, 1]]:
        ni, nj = i + movei, j + movej
        if (H <= ni or W <= nj):
            continue
        if m[ni][nj] == '#':
            c = counts[i][j] + 1
        else:
            c = counts[i][j]
        if counts[ni][nj] < 0:
            counts[ni][nj] = c
        else:
            if counts[ni][nj] > c:
                counts[ni][nj] = c
        if ni < H and nj < W:        
            q.append([ni, nj])
print(counts[H-1][W-1])

Submission status: Time Limit Exceeded

Solution code:
import itertools
import sys
sys.setrecursionlimit(10**9)

INF = 10**20
def main():
    H,W = map(int,input().split())
    s = [[""] * W for _ in range(H)]
    for i in range(H):
        S = input()
        for j in range(W):
            s[i][j] = S[j]

    s_e = (s[0][0] == "#") + 0
    s_e += (s[H-1][W-1] == "#") + 0
    s[H-1][W-1] = "."


    def pos(r,c):
        return r*H+c+1

    max_edge = max(H+1,W+1) ** 2
    m = [0] * max_edge
    dp = [[INF] * max_edge for _ in range(max_edge)]
    for r in range(H):
        for c in range(W):
            cost = (s[r][c] == "#") + 0
            if r == c:
                dp[pos(r,c)][pos(r,c)] = 0

            if r > 0:
                dp[pos(r-1,c)][pos(r,c)] = cost
                dp[pos(r,c)][pos(r-1,c)] = cost
            if c > 0:
                dp[pos(r,c-1)][pos(r,c)] = cost
                dp[pos(r,c)][pos(r,c-1)] = cost


    for k in range(max_edge):
        for i in range(max_edge):
            for j in range(max_edge):
                dp[i][j] = min(dp[i][j], dp[i][k]+dp[k][j])

    print(dp[1][pos(H-1,W-1)] + s_e)

if __name__ == "__main__":
  main()

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
import sys

h,w = [int(x) for x in input().split()]
m = []
for _ in range(h):
    m.append(list(input()))
ans = 0
if m[0][0]=="#":
    m[0][0]="."
    ans+=1
if m[h-1][w-1]=="#":
    m[h-1][w-1]="."
    ans += 1

q = deque()
v = deque()
q.append([0,0,0])
num = 10**10
while q or v:
    if q:
        p = q.pop()
        if p[0]==h-1 and p[1]==w-1:
            num = min(num,p[2])
            continue
        for dy,dx in [[1,0],[0,1]]:
            ny = p[0]+dy
            nx = p[1]+dx
            if 0<=ny<h and 0<=nx<w:
                if m[ny][nx]==".":
                    q.append([ny,nx,p[2]])
                else:
                    v.append([ny,nx,p[2]+1])
    else:
        z = v.pop()
        for dy,dx in [[1,0],[0,1]]:
            ny = z[0]+dy
            nx = z[1]+dx
            if 0<=ny<h and 0<=nx<w:
                if m[ny][nx]==".":
                    q.append([ny,nx,z[2]])
                else:
                    v.append([ny,nx,z[2]+1])

print(ans+num)

Submission status: Time Limit Exceeded

Solution code:
import sys

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

INF=1000
mymap=list()

for i in range(H):
    mymap.append(input().rstrip())

#print(mymap)

costmap=[[INF for i in range(W)] for j in range(H)]
#print(costmap)

def make_costmap(i,j,prev_state,c):
    #print(i,j,prev_state,c)
    state=mymap[i][j]
    if (prev_state == "." and state=="#"):
        c+=1
    if costmap[i][j]>c:
        costmap[i][j]=c
    if (i<H-1):
        make_costmap(i+1,j,state,c)
    if (j<W-1):        
        make_costmap(i,j+1,state,c)
    return

make_costmap(0,0,".",0)

#for i in range(H):
#    print(mymap[i])
#for i in range(H):
#    print(costmap[i])

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

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
H,W = map(int,input().split())
S = []
for i in range(H):
    S.append(list(input()))

sx, sy = (0,0)
gx, gy = (W-1,H-1)

vx = [1,0]
vy = [0,1]

d = [[-1,0] for _ in range(H*W)]
xy = lambda x,y: x + y*W

def bfs():
    while(len(q)):
        x, y = q.popleft()
        for i in range(2):
            nx = x + vx[i]
            ny = y + vy[i]
            if nx < W and ny < H:
                # print('nx,ny=',nx,ny)
                tmp = d[xy(x,y)].copy()
                tmp[0] += 1
                if S[ny][nx] == '#':
                    tmp[1] += 1
                if d[xy(nx,ny)][0] == -1 or (d[xy(nx,ny)][0] >= tmp[0] and d[xy(nx,ny)][1] >= tmp[1]):
                    q.append((nx,ny))
                    d[xy(nx,ny)] = tmp
#                print(x,y,nx,ny,d)
#                if (nx, ny) == (gx, gy): return

q = deque()
q.append((sx,sy))
d[xy(sx,sy)][0] = 0
if S[0][0] == '#': d[xy(sx,sy)][1] = 1
bfs()
# print(d)
# print(d[xy(gx,gy)])
print(d[xy(gx,gy)][1])

Submission status: Time Limit Exceeded

Solution code:
h,w = map(int, input().split())
grid = []
for i in range(h):
    grid.append(list(input()))
#色が変わるところでコスト
inf = 10**9
#x,y渡すと、（ｈ、ｗ）に入ってるかどうか判定
def check(s,t):
    if (0 <=  s <= h - 1) and (0 <= t <= w - 1):
        return True
    else:
        return False
#graph => そこまでの距離を保存した二次元配列　grid=>与えられた迷路
adjacent_list = [[] for i in range(h*w+1)]
for i in range(h):
    for j in range(w):
        if i == (h-1) and j == (w-1):
            continue
        if j != (w-1):
            if grid[i][j] != grid[i][j+1] and grid[i][j] == '#':
                adjacent_list[w*i + (j + 1)].append([w*(i) + (j + 2), 1])
            else:
                adjacent_list[w*i + (j + 1)].append([w*(i) + (j + 2), 0])
        if i != (h-1):
            if grid[i][j] != grid[i+1][j] and grid[i][j] == '#':
                adjacent_list[w*i + (j + 1)].append([w*(i + 1) + (j + 1), 1])
            else:
                adjacent_list[w*i + (j + 1)].append([w*(i + 1) + (j + 1), 0])
finished = set()
def dfs(node,cost):
    finished.add(node)
    for i in adjacent_list[node]:
        dist[i[0]] = min(dist[i[0]],dist[node] + i[1])
        dfs(i[0],i[1])
dist = [inf for i in range(h*w+1)]
dist[1] = 0
dfs(1,0)
if grid[-1][-1] == '#':
    dist[-1] += 1
print(dist[-1])

Submission status: Time Limit Exceeded

Solution code:
h,w=map(int,input().split())
s=[list(input()) for _ in range(h)]
q=[(0,0)]
g=[[1000]*w for  _ in range(h)]
g[0][0]=0
if s[0][0]=="#":
    g[0][0]=1
from collections import deque
q=deque([(0,0)])

while q:
    x,y=q.popleft()
    if x==w and y==h:
        break
    for dx,dy in ((1,0),(0,1)):
        if not(0 <= x+dx < w) or not(0 <= y+dy < h):
            continue
        elif s[y+dy][x+dx] == '#':
            g[y+dy][x+dx]=min(g[y][x]+1,g[y+dy][x+dx])
        else:
            g[y+dy][x+dx]=min(g[y][x],g[y+dy][x+dx])
        q.append((x+dx,y+dy))
    

print(g[-1][-1])

Submission status: Time Limit Exceeded

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

count = [float('inf')]
def dfs(x,y,cnt):
    if x==H-1 and y==W-1:
        if count[0] > cnt:
            count[0] = cnt
        return
    if y < W-1:
        if field[x][y]=='#':
            dfs(x,y+1,cnt+1)
        else:
            dfs(x,y+1,cnt)
    if x < H-1:
        if field[x][y]=='#':
            dfs(x+1,y,cnt+1)
        else:
            dfs(x+1,y,cnt)


if field[0][0]=='#':
    dfs(0,0,1)
else:
    dfs(0,0,0)

print(count[0])

Submission status: Time Limit Exceeded

Solution code:
import copy
from collections import deque


def bfs(s1,s2):
    que = deque()
    que.append([0, 0])
    cs = copy.deepcopy(s)
    if cs[s1][s2] == '#':
        cs[s1][s2] = 1
    else:
        cs[s1][s2] = 0
    while len(que) != 0:
        p = que.popleft()
        for i in range(2):
            nextX = p[0] + moveR[i]
            nextY = p[1] + moveC[i]
            if 0 <= nextX and nextX < H\
                and 0 <= nextY and nextY < W:
                if cs[nextX][nextY] == '#':
                    cs[nextX][nextY] = cs[p[0]][p[1]] + 1
                elif cs[nextX][nextY] == '.':
                    cs[nextX][nextY] = cs[p[0]][p[1]]
                else:
                    tmp = 0
                    if s[nextX][nextY] == '#':
                        tmp = 1
                    cs[nextX][nextY] = min(cs[p[0]][p[1]] + tmp, cs[nextX][nextY])
                que.append([nextX, nextY])
    print(cs[-1][-1])

H, W = map(int, input().split())
s = [list(input()) for _ in range(H)]
ans = 10 ** 9
moveR = [0, 1]
moveC = [1, 0]
bfs(0,0)

Submission status: Time Limit Exceeded

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

def dfs(row, col, count):
    global n, m
    global grid

    if row == n-1 and col == m-1:
        if grid[row][col] == '.':
            count += 1
        counts.append(count)
        return
    else:
        if count + (n-1-row) + (m-1-col) < max(counts):
            return
        if grid[row][col] == '.':
            count += 1
        if row+1 <= n-1:
            dfs(row+1,col,count)
        if col+1 <= m-1:
            dfs(row,col+1,count)


n, m = map(int, input().split())
counts = [0]
grid = [[0 for i in range(m)]for j in range(n)]
for row in range(n):
    temp = input()
    for col in range(m):
        grid[row][col] = temp[col]

dfs(0,0,0)
print(m+n-1 - max(counts))

Submission status: Time Limit Exceeded

Solution code:
H, W = map(int, input().split())
maze = [list(input()) for _ in range(H)]
done = [[10**4 + 1]*(W) for _ in range(H)]

min_count = 10 ** 4 + 1

def dfs(h, w, before_black, count):
    if maze[h][w] == "#":
        is_black = True
        if not before_black:
            count += 1
    else:
        is_black = False
    if done[h][w] < count:
        return
    done[h][w] = count
    if h == H-1 and w == W-1:
        global min_count
        if count < min_count:
            min_count = count
    elif h == H-1:
        dfs(h, w+1, is_black, count)
    elif w == W-1:
        dfs(h+1, w, is_black, count)
    else:
        dfs(h+1, w, is_black, count)
        dfs(h, w+1, is_black, count)

dfs(0,0,False,0)

print(min_count)

Submission status: Time Limit Exceeded

Solution code:
import bisect
import math
from collections import deque

def sRaw():
    return input().rstrip("\r")


def iRaw():
    return int(input())


def ssRaw():
    return input().split()


def isRaw():
    return list(map(int, ssRaw()))


INF = 1 << 29


def main():
    H,W  =isRaw()
    ss = [sRaw() for _ in range(H)]
    memo = [[INF for _ in range(W)] for _ in range(H)]
    qu = deque()
    isF = 1 if ss[0][0] == "#" else 0
    qu.append([0, 0, isF, isF])
    ans = INF
    while len(qu) != 0:
        x, y, z, isF = qu.popleft()
        if x != W-1:
            nx = x+1
            nisF = 1 if ss[y][nx] == "#" else 0
            z2 = z
            if nisF == 1 and isF == 0:
                z2 += 1
            if memo[y][nx] < z2:
                continue
            memo[y][nx]=z2
            if nx == W-1 and y == H-1:
                ans = min(ans, z2)
                continue
            qu.append([nx, y, z2, nisF])
        if y != H-1:
            ny = y+1
            nisF = 1 if ss[ny][x] == "#" else 0
            z2 = z
            if nisF == 1 and isF == 0:
                z2 += 1
            if memo[ny][x] < z2:
                continue
            memo[ny][x] = z2
            if x == W-1 and ny == H-1:
                ans = min(ans, z2)
                continue
            qu.append([x, ny, z2, nisF])

    return ans

    
if __name__ == "__main__":
    print(main())

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
import sys
import heapq
from collections import deque

def solve(H: int, W: int, s: "List[str]"):
    minScore = 10**16
    def isBlock(x,y):
        return s[y][x] == "#"
    first = isBlock(0,0)
    current = deque([(0,0)])
    map = [[None for j in range(H)] for i in range(W)]
    map[0][0] = (1,True) if first else (0,False)
    def addNextIfCan(x,y,prevScore,prevBlock):
        if x >= W or y >= H:
            return
        c = isBlock(x,y)
        current.appendleft((x,y))
        cScore = prevScore + 1 if c and not prevBlock else prevScore
        if map[x][y] == None:
            map[x][y] = (cScore,c)
            return
        if map[x][y][0] > prevScore:
            map[x][y] = (cScore,c)
        elif c and map[x][y][0] == prevScore:
            map[x][y] = (cScore,c)
    
    while len(current) > 0:
        n = current.pop()
        prevScore = map[n[0]][n[1]][0]
        prevBlock = map[n[0]][n[1]][1]
        addNextIfCan(n[0]+1,n[1],prevScore,prevBlock)
        addNextIfCan(n[0],n[1]+1,prevScore,prevBlock)
    print(map[W-1][H-1][0])
    return


# 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 = int(next(tokens))  # type: int
    W = int(next(tokens))  # type: int
    s = [next(tokens) for _ in range(H)]  # type: "List[str]"
    solve(H, W, s)

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:

#####

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

#####

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


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

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


def travel(colors, h, w, row0, col0, targetColor, flipSize, nextParams: deque):
# 	print()
# 	print("row0",row0,"col0",col0,"flipSize",flipSize)
	
	visited=np.zeros((h-row0, w-col0), np.bool)
	visited[0,0]=True
	next=set()
	for hi in range(row0, h):
		for wi in range(col0, w):
			c=colors[hi,wi]==targetColor
			if hi>0 and visited[hi-1-row0,wi-col0]:
				if c:
					visited[hi-row0,wi-col0]=True
				else:
					next.add((hi,wi))
			if wi>0 and visited[hi-row0,wi-1-col0]:
				if c:
					visited[hi-row0,wi-col0]=True
				else:
					next.add((hi,wi))
	
	if visited[h-1-row0,w-1-col0]:
# 		print("found")
# 		return flipSize
		print(flipSize)
		sys.exit(0)
					
# 	print(next)
	if len(next)==0: return None
	minFlipSize=None
	if targetColor: nextFlipSize=flipSize+1
	else: nextFlipSize=flipSize
	for nr,nc in next:
		p=(colors, h, w, nr, nc, not targetColor, nextFlipSize)
		nextParams.append(p)


def main(inputs):
	h,w=getIntList(inputs[0])
	colors=np.empty((h,w),np.bool)
	for hi in range(h):
		for wi in range(w):
			colors[hi,wi]=inputs[1+hi][0][wi]=="."
# 	print(colors)
	
	if colors[0,0]: nextFlipSize=0
	else: nextFlipSize=1
	
	nextParams=deque()
	p=(colors, h, w, 0, 0, colors[0,0], nextFlipSize)
	nextParams.append(p)
	
	while len(nextParams)>0:
		param=nextParams.popleft()
		travel(*param, nextParams=nextParams)
# 	print("flipSize",flipSize)
# 	print(flipSize)
	

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

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(10**6)

def LI():
	return [ int(s) for s in input().split() ]

H,W = LI()
field = [ list(input()) for _ in range(H) ]

def dfs(i,j,cnt):
  if field[i][j] == '#':
    cnt+=1
  if i==H-1 and j==W-1:
    return cnt
  if i < H-1 and j < W-1:
    return min(dfs(i+1,j,cnt),dfs(i,j+1,cnt))
  if i < H-1:
    return dfs(i+1,j,cnt)
  if j < W-1:
    return dfs(i,j+1,cnt)

print(dfs(0,0,0))

Submission status: Time Limit Exceeded

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

def main():
    h,w=map(int,input().split())
    s=[list(input()) for _ in range(h)]
    flg=['#','.']
    def dfs(x,y,f):
        a,b=0,0
        if x<h-1:
            if s[x+1][y]==flg[f]:
                a=dfs(x+1,y,f)
            else:
                a=dfs(x+1,y,(f+1)%2)+1
        if y<w-1:
            if s[x][y+1]==flg[f]:
                b=dfs(x,y+1,f)
            else:
                b=dfs(x,y+1,(f+1)%2)+1
        return min(a,b)

    if s[0][0]=='#':
        print(dfs(0,0,0)+1)
    else:
        print(dfs(0,0,1))
        
if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
# flip = True:その場が黒
def dfs(flip, nowx, nowy, step):
    if nowx == gx and nowy == gy:
        if field[nowy][nowx] == '#':
            step += 1
        elif field[nowy][nowx] == '.' and flip:
            step += 1
        return step
    else:
        if field[nowy][nowx] == '.':
            if flip:
                step += 1
                flip = False
        elif field[nowy][nowx] == '#':
            if flip == False:
                flip = True
        if nowx + 1 == w:
            return dfs(flip, nowx, nowy + 1, step)
        if nowy + 1 == h:
            return dfs(flip, nowx + 1, nowy, step)
        return min(dfs(flip, nowx + 1, nowy, step),
                   dfs(flip, nowx, nowy + 1, step))


h, w = map(int, input().split())
field = [[c for c in input().strip()] for _ in range(h)]
sx, sy = 0, 0
gx, gy = w - 1, h - 1
dirx = [1, 0]
diry = [0, 1]

print(dfs(False, sx, sy, 0))

Submission status: Time Limit Exceeded

Solution code:

def main():


    from collections import deque


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

    q = deque()

    if a[0][0]=='.':
        q.appendleft((0,0,0))
    else:
        q.appendleft((0,0,1))

    while(True):
        f = q.popleft()
        x, y, c = f[0], f[1], f[2]
        if (x,y) == (w-1,h-1):
            print(c)
            break

        for u, v in [(1,0), (0,1)]:
            if x + u <= w - 1 and y + v<= h - 1:
                n = a[x+u][y+v]=='.'
                if n:
                    q.appendleft((x + u, y + v, c + 0))
                else:
                    q.append((x + u, y + v, c + 1))



if __name__=='__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:

def minCost(cost, m, n): 
	if (n < 0 or m < 0): 
		return 10**9+7
	elif (m == 0 and n == 0): 
		return cost[m][n] 
	else: 
		return cost[m][n] + min(minCost(cost,m-1,n),minCost(cost,m,n-1)) 


n,m=map(int,input().split())
a=[]
x=0
for i in range(n):
    s=input().replace('.','0').replace('#','1')
    ss=[int(i) for i in s]
    a.append(ss)
x=minCost(a,n-1,m-1)
print(x)

Submission status: Time Limit Exceeded

Solution code:
# import bisect
from collections import Counter, deque
# import copy
# from heapq import heappush, heappop, heapify
# from fractions import gcd
# import itertools
# from operator import attrgetter, itemgetter
# import math

import sys

# import numpy as np

readline = sys.stdin.readline
MOD = 10 ** 9 + 7
INF = float('INF')
sys.setrecursionlimit(10 ** 5)


def main():
    h, w = list(map(int, readline().split()))

    s = [input() for _ in range(h)]
    n = [[INF] * w for _ in range(h)]

    if s[0][0] == "#":
        wall = 1
        state = True
    else:
        wall = 0
        state = False

    que = deque()
    que.append((0, 0, wall, state))

    while que:
        y, x, wall, state = que.popleft()
        n[y][x] = min(n[y][x], wall)
        ny = y + 1
        nx = x + 1

        if state:
            if ny < h:
                if s[ny][x] == "#":
                    que.append((ny, x, wall, True))
                elif s[ny][x] == ".":
                    que.append((ny, x, wall, False))

            if nx < w:
                if s[y][nx] == "#":
                    que.append((y, nx, wall, True))
                elif s[y][nx] == ".":
                    que.append((y, nx, wall, False))
        else:
            if ny < h:
                if s[ny][x] == "#":
                    que.append((ny, x, wall + 1, True))
                elif s[ny][x] == ".":
                    que.append((ny, x, wall, False))

            if nx < w:
                if s[y][nx] == "#":
                    que.append((y, nx, wall + 1, True))
                elif s[y][nx] == ".":
                    que.append((y, nx, wall, False))

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


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys; sys.setrecursionlimit(2147483647); input = sys.stdin.readline
from math import floor, ceil, sqrt, factorial, log
from collections import Counter, defaultdict, deque
from operator import itemgetter
INF = float('inf'); MOD = 10**9+7
def I(): return int(input())
def MI(): return map(int, input().split())
def LI(): return list(MI())
def LIR(n): return [LI() for i in range(n)]
def IS(): return input().rstrip()

def judge(s, i, j, H, W):
    if i+1 == H and j+1 == W:
        if s[i][j] == '.': return 0
        else: return 1
    elif i+1 == H:
        if s[i][j] == '.': return judge(s, i, j+1, H, W)
        else: return judge(s, i, j+1, H, W)+1
    elif j+1 == W:
        if s[i][j] == '.': return judge(s, i+1, j, H, W)
        else: return judge(s, i+1, j, H, W)+1
    else:
        if s[i][j] == '.': return min(judge(s, i+1, j, H, W), judge(s, i, j+1, H, W))
        else: return min(judge(s, i+1, j, H, W)+1, judge(s, i, j+1, H, W)+1)

def main():
    H, W = MI()
    s = [IS() for i in range(H)]
    print(judge(s, 0, 0, H, W))
if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

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

def bfs(maze,visited,gx,gy):
    stack = deque([[0,0]])
    if maze[0][0] == '#':
        visited[0][0] = 1 
    else:
        visited[0][0] = 0 
    while stack:
        y,x = stack.pop()
        count = visited[y][x]
        
        for j,k in ([1,0],[0,1]):
            new_y,new_x = y+j,x+k
            if  new_x >= gx or  new_y >= gy:
                continue
            elif maze[new_y][new_x] == "#" and maze[y][x] == '.':
                visited[new_y][new_x] = min(count+1,visited[new_y][new_x])
                stack.appendleft([new_y, new_x])
            else:
                visited[new_y][new_x] = min(count,visited[new_y][new_x])
                stack.appendleft([new_y, new_x])
    return visited[gy-1][gx-1]

inf = float('inf')
visited = [[inf]*W for _ in range(H)]
print(bfs(maze,visited,W,H))

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
INF = int(1e9) + 7
h, w = map(int, input().split())
s = []
for i in range(h):
    s.append(list(input()))



def bfs(x, y):
    d = [[INF] * w for i in range(h)]
    dx = [1,0]
    dy = [0,1]
    if s[0][0] == '#':
        d[0][0] = 1
    else:
        d[0][0] = 0
    que = deque([(0, 0)])

    while len(que) != 0:
        val = que.popleft()

        for i in range(2):
            nx = val[0] + dx[i]
            ny = (val[1] + dy[i])
            if nx < h and ny < w:

                que.append((nx, ny))
                if (s[nx][ny] == '#') and (d[nx][ny] > d[val[0]][val[1]]):
                    d[nx][ny] = d[val[0]][val[1]] + 1
                elif s[nx][ny] != '#' and d[nx][ny] < d[val[0]][val[1]]:
                    d[nx][ny] = d[nx][ny]

                else:
                    d[nx][ny] = d[val[0]][val[1]]
    return d[h-1][w-1]
print(bfs(h, w))

Submission status: Time Limit Exceeded

Solution code:
import copy
import queue

def bfs(s1,s2):
    cs = copy.deepcopy(s)
    queueX = queue.Queue()
    queueY = queue.Queue()
    queueX.put(s1)
    queueY.put(s2)
    if cs[s1][s2] == '#':
        cs[s1][s2] = 1
    else:
        cs[s1][s2] = 0
    while queueX.empty() == False:
        x = queueX.get()
        y = queueY.get()

        for i in range(2):
            nextX = x + moveR[i]
            nextY = y + moveC[i]
            if 0 <= nextX and nextX < H\
                and 0 <= nextY and nextY < W:
                if cs[nextX][nextY] == '#':
                    cs[nextX][nextY] = cs[x][y] + 1
                elif cs[nextX][nextY] == '.':
                    cs[nextX][nextY] = cs[x][y]
                else:
                    tmp = 0
                    if s[nextX][nextY] == '#':
                        tmp = 1
                    cs[nextX][nextY] = min(cs[x][y] + tmp, cs[nextX][nextY])
                queueX.put(nextX)
                queueY.put(nextY)
    print(cs[-1][-1])

H, W = map(int, input().split())
s = [list(input()) for _ in range(H)]
ans = 10 ** 9
moveR = [0, 1]
moveC = [1, 0]
bfs(0,0)