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:
h, w = [int(e) for e in input().split()]
S = [input() for e in range(h)]
A = []

def dfs(hp, wp, cnt, white):
    if hp == h - 1 and wp == w - 1:
        if S[hp][wp] == '#':
            cnt += 1

        if cnt == 0:
            print(0)
            exit()

        A.append(cnt)
        return

    if hp < h - 1:
        if (white and S[hp + 1][wp] == '.') or (not white and S[hp + 1][wp] == '#'):
            dfs(hp + 1, wp, cnt, white)
        else:
            if not white and S[hp + 1][wp] == '.':
                dfs(hp + 1, wp, cnt + 1, not white)
            else:
                dfs(hp + 1, wp, cnt, not white)

    if wp < w - 1:
        if (white and S[hp][wp + 1] == '.') or (not white and S[hp][wp + 1] == '#'):
            dfs(hp, wp + 1, cnt, white)
        else:
            if not white and S[hp][wp + 1] == '.':
                dfs(hp, wp + 1, cnt + 1, not white)
            else:
                dfs(hp, wp + 1, cnt, not white)

def main():
    dfs(0, 0, 0, S[0][0] == '.')
    print(min(A))

if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
h, w = map(int,input().split())
map = []
visited = [[10**10]*w for i in range(h)]
for i in range(h):
    map.append(list(input()))
queue = deque()
if map[0][0] == '#':
    queue.append([1,0,0])#[y,x,num]
else:
    queue.append([0,0,0])#[y,x,num]
min = 10**10
flag = 0
while queue:
    num,y,x= queue.popleft()
    if map[y][x] == '#' and flag != 0:
        num = num+1
    if y == h-1 and x == w-1:
        if min > num:
            min = num
            continue
    if y+1 < h and num < min and num <= visited[y+1][x]:
        queue.append([num,y+1,x])
        visited[y+1][x] = num
    if x+1 < w and num < min and num <= visited[y][x+1]:
        queue.append([num,y,x+1])
        visited[y][x+1] = num
    flag = 1
print(min)

Submission status: Time Limit Exceeded

Solution code:
# TLE

import numpy as np
import sys
sys.setrecursionlimit(2000)

H, W = [int(x) for x in input().split()]
s = [list(input()) for i in range(H)]
M = np.array([[ (0 if s[i][j] == '.' else 1) for j in range(W) ] for i in range(H)])

def solve(M):

    Mr = np.copy(M)
    Mc = np.copy(M)


    H = M.shape[0]
    W = M.shape[1]

    ret = 0

    if M.sum() == 0:
        return ret
    elif H == W == 1:
        return M[0][0]


    del_row = 100000
    del_col = 100000
    retr = 0
    retc = 0
    if H > 1:
        if Mr[0][0] == 1:
            h = 1
            w = 1
            # while h < H and M[:h + 1, :w].sum() == (h + 1) * w:
            while h < H and Mr[h][0] == 1:
                h += 1
            # while w < W and Mr[:h, :w + 1].sum() == h * (w + 1):
            while w < W and Mr[:h, w:w + 1].sum() == h:
                w += 1

            for i in range(h):
                for j in range(w):
                    Mr[i][j] = 0
            retr += 1

        del_row = solve(Mr[1:, :])


    if W > 1:

        if Mc[0][0] == 1:

            h = 1
            w = 1

            # while w < W and Mc[:h, :w + 1].sum() == h * (w + 1):
            while w < W and Mc[0][w] == 1:
                w += 1
            # while h < H and Mc[:h + 1, :w].sum() == (h + 1) * w:
            while h < H and Mc[h:h + 1, :w].sum() == w:
                h += 1


            for i in range(h):
                for j in range(w):
                    Mc[i][j] = 0
            retc += 1

        del_col = solve(Mc[:, 1:])

    return min(retr + del_row, retc + del_col)


print(solve(M))

Submission status: Time Limit Exceeded

Solution code:
H,W = map(int,input().split())
p = []
for i in range(H):
    b = list(input())
    b.append(".")
    p.append(b)

p.append(["."]*(W+1))
c = [[10**9]*(W+1) for i in range(H+1)]

if p[0][0] == ".":
    c[0][0] = 0
else:
    c[0][0] = 1

q = [[0,0]]

i = 0
j = 0
while(len(q) != 0):
    i = q[0][0]
    j = q[0][1]
    q.remove([i,j])
    if p[i+1][j] == ".":
        c[i+1][j] = min(c[i][j],c[i+1][j])
    else:
        c[i+1][j] = min(c[i][j]+1, c[i+1][j])
    if p[i][j+1] == ".":
        c[i][j+1] = min(c[i][j],c[i][j+1])
    else:
        c[i][j+1] = min(c[i][j]+1,c[i][j+1])
    if i < H-1:
        q.append([i+1,j])
    if j < W-1:
        q.append([i,j+1])

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

Submission status: Time Limit Exceeded

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

start_point = [0,0]
goal_point = [H,W]
graph = [list(input()) for _ in range(H)]
# print(graph)
# graph = []
# for i in range(H):
#     graph.append(input())
#100000000
dist = [[0 for _ in range(W)] for _ in range(H)]
dx = [1,0]
dy = [0,1]
q = queue.Queue()
q.put([start_point[0],start_point[1]])
# print(q.get())
if graph[0][0] == "#":
    dist[0][0] = 1


def DFS(graph,start_point,goal_point):
    not_visited = []
    not_visited=[[True for i in range(W)] for j in range(H)]
    stack = [start_point]#1.始点のノードを探索待ちスタックに追加


    not_visited[start_point[0]][start_point[1]] = False
    while len(stack) != 0:#2.探索待ちスタックにノードが無ければ終了
          now_point = stack.pop()#2.探索待ちスタックにノードがあれば取り出す
        #   print(now_point)
          for i in range(2):
                if now_point[0]+1 == goal_point[0] and now_point[1]+1 == goal_point[1]:#3.取り出したノードが目的のノードであれば探索終了
                    print(0)
                    return False
                else:
                    serch_point = [now_point[0]+dx[i],now_point[1]+dy[i]]#4.取り出したノードに隣接するノード
                    if 0 <= serch_point[0] < H and 0 <= serch_point[1] < W:#4.隣接するノードが迷路の範囲内かどうか判定
                        if graph[serch_point[0]][serch_point[1]] != "#" and not_visited[serch_point[0]][serch_point[1]]:#4.未探索のノードを探索待ちスタックに追加
                            stack.append([serch_point[0],serch_point[1]])
                            not_visited[serch_point[0]][serch_point[1]] = False
    return True
if DFS(graph, start_point, goal_point):
    while not q.empty():
        v = q.get()
        h,w = v[0],v[1]
        # print(v)
        for i in range(2):
            nh = h + dx[i]
            nw = w + dy[i]
            # print(dist)
            # print("{},{}".format(nh,nw))
            if nh < 0 or nh >= H or nw < 0 or nw >= W:
                continue
            # if dist[nh][nw] != -1:#探索済みか判定
                # continue
            # print(graph[nh][nw])
            if graph[nh][nw] == "#":
                if dist[nh][nw] == 0:
                    dist[nh][nw] = dist[h][w]+1
                else:
                    dist[nh][nw] = min(dist[nh][nw],dist[h][w]+1)
            else:
                # dist[nh][nw] = min(dist[h][w],dist[nh][nw])
                if dist[nh][nw] == 0:
                    dist[nh][nw] = dist[h][w]
                else:
                    dist[nh][nw] = min(dist[h][w],dist[nh][nw])
            q.put([nh,nw])
    print(dist[W-1][H-1])

Submission status: Time Limit Exceeded

Solution code:
import itertools

def main():
    H, W = [int(i) for i in input().split()]
    
    s = []
    for i in range(H):
        s.append(input())
    
    l = [1] * (H - 1) + [0] * (W - 1)

    change = H + W
    for i in set(itertools.permutations(l)):
        r = 0
        c = 0
        m = 0
        if s[r][c] == "#":
            m += 1

        for j in i:
            if j == 1:
                r += 1
            else:
                c += 1
            if s[r][c] == "#":
                m += 1
        change = min(change, m)

    print(change)

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
import copy

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


# h x w のマップのリストを整形
#t = []
#for i in range(h):
#    tmp = []
#    for j in range(w):
#        tmp.append(s[i][j])
#    t.append(tmp)


# 現在地とその距離
if t[0][0] == '#':
    q = list([(0,0,1)])
else:
    q = list([(0,0,0)])

# スタートを設定してsをコピー
#t = copy.deepcopy(t_tmp)
#print(t)
tmp_list = []

tmp_min = 1000000
while q:
    #print(q)
    x,y,c = q[0]
    q.pop(0)

    if (x+1, y+2) == (w, h) or (x+2, y+1) == (w, h):
        #print('continue')
        continue
    pass_ = 0
    #if (x+1,y+1) == (h,w):
    #    continue

    for dx, dy in [(1,0),(0,1)]:
        # 壁を超えるか否か
        nx, ny = x+dx, y+dy
        if 0<=nx<h and 0<=ny<w and t[nx][ny] == '.':
            #print(nx, ny)
            #t[nx][ny] = '#'
            q.append((nx,ny,c))
            pass_ = 1
            if (nx+1,ny+2) == (h, w):
                if t[nx][ny+1] == '.':
                    if tmp_min > c:
                        tmp_min = c
                elif t[nx][ny+1] == '#':
                    if tmp_min > c+1:
                        tmp_min = c+1
            elif (nx+2,ny+1) == (h, w):
                if t[nx+1][ny] == '.':
                    if tmp_min > c:
                        tmp_min = c
                elif t[nx+1][ny] == '#':
                    if tmp_min > c+1:
                        tmp_min = c+1

    
        elif 0<=nx<h and 0<=ny<w and t[nx][ny] == '#' and pass_ == 0:
            #t[nx][ny] = '#'
            q.append((nx,ny,c+1))
            
            if (nx+1,ny+2) == (h, w):
                if t[nx][ny+1] == '.':
                    if tmp_min > c+1:
                        tmp_min = c+1
                elif t[nx][ny+1] == '#':
                    if tmp_min > c+2:
                        tmp_min = c+2

            elif (nx+2,ny+1) == (h, w):
                if t[nx+1][ny] == '.':
                    if tmp_min > c+1:
                        tmp_min = c+1
                elif t[nx+1][ny] == '#':
                    if tmp_min > c+2:
                        tmp_min = c+2
    
    q = list(set(q))

#print(tmp_list)
print(tmp_min)

#if tmp_list == []:
#    print('0')
#else:
#    print(min(tmp_list))

Submission status: Time Limit Exceeded

Solution code:
import itertools
HW=input().split()
H=int(HW[0])
W=int(HW[1])
gyouretsu=[]
for i  in range(H) :
  gyouretsu.append(input())
 
seq=[]
for i in range(W-1) :
  seq.append(True)
for i in range(H-1) :
  seq.append(False) 

list1=list(set(itertools.permutations(seq)))
#list2=[[True,True,True,True,False,False,False,False]]
count_list=[]
for path in list1 :
  x=1
  y=1
  count=0
  houkou=None
  katamari=False
  
  if gyouretsu[x-1][y-1]=='#' :
    katamari=True
    count+=1
  for s in path :
    
    if s :
      y+=1
    else :
      x+=1
    
    if gyouretsu[y-1][x-1]=='#' :
      
      if not katamari :
        katamari=True
        count+=1
      else :
        if houkou==None :
          houkou=i
        elif houkou!=i:
          count+=1
          katamari=False
          houkou=None
    else :
      houkou=None
      katamari=False
  count_list.append(count)
  
print(min(count_list))

Submission status: Time Limit Exceeded

Solution code:
# coding: utf-8
# Your code here!
# coding: utf-8
import sys
sys.setrecursionlimit(10000000)

#const
dxdy=((1,0),(0,1))
# my functions here!
def pin(type=int):
    return map(type,input().rstrip().split())
    

#絶対TLEする！A問題のpython回答はこちら！！！！

def sx(h,w,ans,flag=0):#depth-first? search functionを障害物を消しながら行う
    global res
    res+=1
    #print(res)
    
    if h>=H or w>=W:
        #print("そとやんけ！")
        return#迷路の外におる
    if h==H-1 and w==W-1:
        if maze[h][w]=="#":ans+=1-flag
        if dp[h][w]>=ans:
            dp[h][w]=ans        
       # print("end")
        return
    if maze[h][w]==".":#普通のサーチする
        if dp[h][w]>=ans:
            dp[h][w]=ans
            for d in dxdy:
                sx(h+d[0],w+d[1],ans)
    else:
        ans+=(1-flag)
        if dp[h][w]>=ans:
            dp[h][w]=ans
            for d in dxdy:
                sx(h+d[0],w+d[1],ans,1)
    
        
def resolve():
    
    global anss ,dp,H,W,maze
    global res
    res=0
    H,W=pin()
    dp=[[(H+W)]*W for _ in range(H)]
    
    maze=tuple(tuple(input())for i in range(H))
    
    sx(0,0,0,0)
    #print(min(anss),len(anss),res)
    anss=[]
    print(dp[H-1][W-1])
    
"""
#B

def resolve():
    N,=pin()
    list_x=[int(i) for i in tuple(input())]
    #print(list_x)
    temp=[abs(list_x[i+1]- list_x[i]) for i in range(N-1) if list_x[i+1]-list_x[i]!=0]

    ans=sum([(temp[j+1]-temp[j]) for j in range(len(temp)-1) if (temp[j+1]-temp[j])!=0])
    print(abs(ans))

"""
"""         
#printデバッグ消した？
#前の問題の結果見てないのに次の問題に行くの？
"""
"""
お前カッコ閉じるの忘れてるだろ
"""

if __name__=="__main__":resolve()

Submission status: Time Limit Exceeded

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

WALL = '#'
stack = [(0, 0, 0)]
min_cnt = H * W

# BFS
while stack:
    """
    stack取り出す
    調べる
    stack
    """
    y, x, cnt = stack.pop()

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

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

    next_y = y + 1
    next_x = x + 1

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

print(min_cnt)

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)]
    b = [deque() for _ in range(h+w-1)]

    n = a[0][0] == '.'
    if n:
        b[0].append((0, 0))
    else:
        b[1].append((0, 0))

    k = 0
    while True:
        if len(b[k])==0:
            k+=1
            continue
        f = b[k].pop()
        x, y = f[0], f[1]

        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(k + n)
                    exit()

                n = a[x + u][y + v] == '.'
                if n:
                    b[k].append((x + u, y + v))
                else:
                    b[k+1].append((x + u, y + v))


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
q = deque()
h,w=map(int,input().split())
global finished 
finished = set()
c=[]
for i in range(h):
    c.append(list(map(str,input())))
cans=[[300 for _ in range(w)] for _ in range(h)]
#print(cans)
q.append([0,0,0])
if c[h-1][w-1]=='#':
    asd=1
else:
    asd=0
c[h-1][w-1]='s'

def check(x,y):
    if 0<=x and x<h:
        if 0<=y and y<w:
            return True
    return False
global ans
ans=1000

def search():
    while (q):
        x,y,count=q.pop()
        #print(q)
        global ans
        
        if check(x,y)==False :
            continue

        else:
            if c[x][y]=='#':
                if cans[x][y]==300 or count+1<=cans[x][y]:
                    cans[x][y]=count+1
                    q.append([x,y+1,count+1])
                    q.append([x+1,y,count+1])
                else:
                    continue
            else:
                if cans[x][y]==300 or count<=cans[x][y]:
                    cans[x][y]=count
                    q.append([x,y+1,count])
                    q.append([x+1,y,count])
                else:
                    continue
                #print(ans)
     
search()
#for i in range(h):
 #   print(cans[i])
           
print(cans[h-1][w-1]+asd)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
import copy

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


# h x w のマップのリストを整形
t = []
for i in range(h):
    tmp = []
    for j in range(w):
        tmp.append(s[i][j])
    t.append(tmp)


# 現在地とその距離
if s[0][0] == '#':
    q = list([(0,0,1)])
else:
    q = list([(0,0,0)])

# スタートを設定してsをコピー
#t = copy.deepcopy(t_tmp)
#print(t)
tmp_list = []

tmp_min = 1000000
while q:
    #print(q)
    x,y,c = q[0]
    q.pop(0)

    if (x+1, y+2) == (w, h) or (x+2, y+1) == (w, h):
        #print('continue')
        continue
    pass_ = 0
    #if (x+1,y+1) == (h,w):
    #    continue

    for dx, dy in [(1,0),(0,1)]:
        # 壁を超えるか否か
        nx, ny = x+dx, y+dy
        if 0<=nx<h and 0<=ny<w and t[nx][ny] == '.':
            #print(nx, ny)
            #t[nx][ny] = '#'
            q.append((nx,ny,c))
            pass_ = 1
            if (nx+1,ny+2) == (h, w):
                if t[nx][ny+1] == '.':
                    if tmp_min > c:
                        tmp_min = c
                elif t[nx][ny+1] == '#':
                    if tmp_min > c+1:
                        tmp_min = c+1
            elif (nx+2,ny+1) == (h, w):
                if t[nx+1][ny] == '.':
                    if tmp_min > c:
                        tmp_min = c
                elif t[nx+1][ny] == '#':
                    if tmp_min > c+1:
                        tmp_min = c+1

    
        elif 0<=nx<h and 0<=ny<w and t[nx][ny] == '#' and pass_ == 0:
            #t[nx][ny] = '#'
            q.append((nx,ny,c+1))
            
            if (nx+1,ny+2) == (h, w):
                if t[nx][ny+1] == '.':
                    if tmp_min > c+1:
                        tmp_min = c+1
                elif t[nx][ny+1] == '#':
                    if tmp_min > c+2:
                        tmp_min = c+2

            elif (nx+2,ny+1) == (h, w):
                if t[nx+1][ny] == '.':
                    if tmp_min > c+1:
                        tmp_min = c+1
                elif t[nx+1][ny] == '#':
                    if tmp_min > c+2:
                        tmp_min = c+2
    
    q = list(set(q))

#print(tmp_list)
print(tmp_min)

#if tmp_list == []:
#    print('0')
#else:
#    print(min(tmp_list))

Submission status: Time Limit Exceeded

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

WALL = '#'
stack = [(0, 0, 0)]
min_cnt = H * W

# BFS
while stack:
    """
    stack取り出す
    調べる
    stack
    """
    y, x, cnt = stack.pop()

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

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

    next_y = y + 1
    next_x = x + 1

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

print(min_cnt)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
H, W = map(int, input().split())
M = []

for i in range(H):
    line = list(input())
    M.append(line)
matrix = np.array(M)




def reverse_row(M):
    col, row = M.shape
    M_c = M.copy()

    for i in range(1, row):
        if M_c[0, i] == ".":
            break
        else:
            M_c[0, i] = "."
    return M_c

def reverse_col(M):
    col, row = M.shape
    M_c = M.copy()

    for i in range(1, col):
        if M_c[i, 0] == ".":
            break
        else:
            M_c[i, 0] = "."
    return M_c

def route(M):
    col, row = M.shape
    if row == 1 and col == 1:
        return 0

    elif row == 1:
        if M[1, 0] == ".":
            return route(M[1:, :])
        else:
            M_r = reverse_col(M)
            return route(M_r[1:, :]) + 1

    elif col == 1:
        if M[0, 1] == ".":
            return route(M[:, 1:])
        else:
            M_r = reverse_row(M)
            return route(M_r[:, 1:]) + 1

    elif M[1, 0] == "." and M[0, 1] == ".":
        return min(route(M[1:, :]), route(M[:, 1:]))

    elif M[1, 0] == "." and M[0, 1] == "#":
        M_r = reverse_row(M)
        return min(route(M[1:, :]), route(M_r[:, 1:]) + 1)

    elif M[1, 0] == "#" and M[0, 1] == ".":
        M_r = reverse_col(M)
        return min(route(M_r[1:, :]) + 1, route(M[:, 1:]))

    elif M[1, 0] == "#" and M[0, 1] == "#":
        M_r1 = reverse_row(M)
        M_r2 = reverse_col(M)
        return min(route(M_r2[1:, :]) + 1, route(M_r1[:, 1:]) + 1)

def main():
    if matrix[0, 0] == "#":
        matrix[0, 0] = "."
        M_r1 = reverse_row(matrix)
        M_r2 = reverse_col(matrix)
        ans = min(route(M_r1) + 1, route(M_r2) + 1)
    else:
        ans = route(matrix)

    print(ans)

main()

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
import sys
sys.setrecursionlimit(2000)

H, W = [int(x) for x in input().split()]
s = [list(input()) for i in range(H)]
M = np.array([[ (0 if s[i][j] == '.' else 1) for j in range(W) ] for i in range(H)])

def solve(M):

    Mr = np.copy(M)
    Mc = np.copy(M)


    H = M.shape[0]
    W = M.shape[1]

    ret = 0

    if M.sum() == 0:
        return ret
    elif H == W == 1:
        return M[0][0]


    del_row = 100000
    del_col = 100000
    retr = 0
    retc = 0
    if H > 1:
        if Mr[0][0] == 1:
            h = 1
            w = 1
            while h < H and M[:h + 1, :w].sum() == (h + 1) * w:
                h += 1
            while w < W and M[:h, :w + 1].sum() == h * (w + 1):
                w += 1

            for i in range(h):
                for j in range(w):
                    Mr[i][j] = 0
            retr += 1

        del_row = solve(Mr[1:, :])


    if W > 1:

        if Mc[0][0] == 1:

            h = 1
            w = 1

            while w < W and Mc[:h, :w + 1].sum() == h * (w + 1):
                w += 1
            while h < H and Mc[:h + 1, :w].sum() == (h + 1) * w:
                h += 1


            for i in range(h):
                for j in range(w):
                    Mc[i][j] = 0
            retc += 1

        del_col = solve(Mc[:, 1:])

    return min(retr + del_row, retc + del_col)


print(solve(M))

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
q = deque()
h,w=map(int,input().split())
global finished 
finished = set()
c=[]
for i in range(h):
    c.append(list(map(str,input())))
q.append([0,0,0])
if c[h-1][w-1]=='#':
    asd=1
else:
    asd=0
c[h-1][w-1]='s'

def check(x,y):
    if 0<=x and x<h:
        if 0<=y and y<w:
            return True
    return False
global ans
ans=1000

def search():
    while (q):
        x,y,count=q.popleft()
        #print("s")
        global ans
        
        if check(x,y)==False :
            continue

        else:
            if c[x][y]=='#':
                q.append([x,y+1,count+1])
                q.append([x+1,y,count+1])
            else:
                q.appendleft([x,y+1,count])
                q.appendleft([x+1,y,count])
            finished.add((x,y))
            if c[x][y]=="s":
                return count
print(search()+asd)

Submission status: Time Limit Exceeded

Solution code:
def flip_count (r, c):
  if r == H - 1 and c == W - 1:
    if s[r][c] == "#":
      return 1
    else:
      return 0
  #右に行ったとき
  if c == W - 1:
    count_right = 10000
  else:
    count_right = flip_count (r, c + 1)
    if s[r][c] == "#" and s[r][c + 1] == ".":
      count_right += 1
  #下に行ったとき
  if r == H - 1:
    count_down = 10000
  else:
    count_down = flip_count (r + 1, c)
    if s[r][c] == "#" and s[r + 1][c] == ".":
      count_down += 1
  return min(count_right, count_down)

H, W = input().split()
W = int (W)
H = int (H)
s = []
for i in range(H):
  s.append(input())
print (flip_count(0, 0))

Submission status: Time Limit Exceeded

Solution code:
H, W = map(int, input().split())
leng = 0
mapList=[]
while True:
    try:
        mapList.append(input())
        leng+=1
    except:
        break;
row = len(mapList[0])

score = [9999]
h = H - 1
w = W - 1

def bfs(p, q, count):
  if(mapList[p][q] == '#'):
    count += 1
  if(count>=max(score)):
    return
  if(p == h and q == w):
    score.append(count)
    return
  
  elif(p == h or p == leng):
    bfs(p, q+1, count)
  elif(q == w or q == row):
    bfs(p+1, q, count)
  else:
    bfs(p, q+1, count)
    bfs(p+1, q, count)
  return
   

point = [[0]*row for j in range(leng)]
bfs(0, 0, 0)

print(min(score))

Submission status: Time Limit Exceeded

Solution code:
h, w = [int(e) for e in input().split()]
S = [input() for e in range(h)]
A = []

def dfs(hp, wp, cnt, white):
    if hp == h - 1 and wp == w - 1:
        if S[hp][wp] == '#':
            cnt += 1

        A.append(cnt)
        return

    if hp < h - 1:
        if (white and S[hp + 1][wp] == '.') or (not white and S[hp + 1][wp] == '#'):
            dfs(hp + 1, wp, cnt, white)
        else:
            if not white and S[hp + 1][wp] == '.':
                dfs(hp + 1, wp, cnt + 1, not white)
            else:
                dfs(hp + 1, wp, cnt, not white)

    if wp < w - 1:
        if (white and S[hp][wp + 1] == '.') or (not white and S[hp][wp + 1] == '#'):
            dfs(hp, wp + 1, cnt, white)
        else:
            if not white and S[hp][wp + 1] == '.':
                dfs(hp, wp + 1, cnt + 1, not white)
            else:
                dfs(hp, wp + 1, cnt, not white)

def main():
    dfs(0, 0, 0, S[0][0] == '.')
    print(min(A))

if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

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

ds = [(1, 0), (0, 1)]
ans = []

def dfs(x, y, m):
    if board[y][x] == "#":
        m += 1
    if x == w - 1 and y == h - 1:
        ans.append(m)
        return
    temp = board[y][x]
    board[y][x] = "x"
    for (dx, dy) in ds:
        if x + dx < w and y + dy < h and board[y + dy][x + dx] != "x":
            dfs(x + dx, y + dy, m)
    board[y][x] = temp
        
dfs(0, 0, 0)
print(min(ans))

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, depth, nextParams: deque, usedRC0: set):
	
	if (row0,col0) in usedRC0: return None
	
# 	print()
# 	print("row0",row0,"col0",col0,"flipSize",flipSize)
	
	visited=np.zeros((h-row0, w-col0), np.bool)
	visited[0,0]=True
	next=set()
	nextUsedRC0=set()
	nextUsedRC0.add((row0,col0))
	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]:
				hwi=(hi,wi)
				if c:
					visited[hi-row0,wi-col0]=True
					if hwi in usedRC0: break
					nextUsedRC0.add(hwi)
				else:
					next.add(hwi)
			if wi>0 and visited[hi-row0,wi-1-col0]:
				hwi=(hi,wi)
				if c:
					visited[hi-row0,wi-col0]=True
					if hwi in usedRC0: break
					nextUsedRC0.add(hwi)
				else:
					next.add(hwi)
		if not visited[hi-row0].any(): break
	usedRC0.update(nextUsedRC0)
	
	if visited[h-1-row0,w-1-col0]:
# 		print("found")
		print(flipSize)
		sys.exit(0)
					
# 	print("next",next)
	
	if len(next)==0: return None
	
	if targetColor: nextFlipSize=flipSize+1
	else: nextFlipSize=flipSize
	
	for nrc in next:
		if nrc in usedRC0: continue
		p=(colors, h, w, nrc[0], nrc[1], not targetColor, nextFlipSize, depth+1)
		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]=="."


# 	h=20
# 	w=20
# 	np.random.seed(0)
# 	colors=np.random.randint(0,2,(h,w))

# 	from matplotlib import pyplot as plt
# 	for hi in range(h):
# 		for wi in range(w):
# 			plt.annotate(str((hi,wi)), (wi-0.5,hi), color="g")
# 	plt.imshow(colors)
# 	plt.show()
			
# 	print(colors.astype(np.int32))
	
	if colors[0,0]: nextFlipSize=0
	else: nextFlipSize=1
	
	nextParams=deque()
	p=(colors, h, w, 0, 0, colors[0,0], nextFlipSize, 0)
	nextParams.append(p)
	
	usedRC0=set()
	while len(nextParams)>0:
		nextDepth=nextParams[0][-1]
		nextQ=[]
		while len(nextParams)>0 and nextParams[0][-1]==nextDepth:
			nextQ.append(nextParams.popleft())
		
		nextQ=sorted(nextQ, key=lambda x: (x[3],x[4]))
		for param in nextQ:
			travel(*param, nextParams=nextParams, usedRC0=usedRC0)


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