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
sys.setrecursionlimit(10 ** 6)
input = sys.stdin.readline
H, W = [int(x) for x in input().strip().split()]
G = [0 for _ in range(H)]
C = [[float('inf') for _ in range(W)] for _ in range(H)]

for h in range(H):
    G[h] = list(input().strip())

def dfs(r, c, cost):
    # print(' -- dfs --')
    C[r][c] = cost
    ret = deque([])
    q = deque([(r, c)])
    while q:
        cr, cc = q.popleft()
        # print('    cr = {}, cc = {}'.format(cr, cc))
        for i, j in [(0, 1), (1, 0)]:
            if not(0 <= cr + i < H and 0 <= cc + j < W):
                continue
            if C[cr+i][cc+j] != float('inf'):
                continue
            if G[r][c] == G[cr+i][cc+j]:
                C[cr+i][cc+j] = cost
                q.append((cr+i, cc+j))
            else:
                ret.append((cr+i, cc+j))
    # print(ret)
    return ret

q = deque([(0, 0)])
cost = 0
while True:
    # print('q = {}'.format(q))
    nq = deque([])
    if G[q[0][0]][q[0][1]] == '#':
        cost += 1
    for r, c in q:
        # print('  r = {}, c = {}'.format(r, c))
        nq.extend(dfs(r, c, cost))
    q = nq
    # print(C)
    # print('nq = {}'.format(nq))
    if C[H-1][W-1] != float('inf'):
        print(C[H-1][W-1])
        exit()

Submission status: Time Limit Exceeded

Solution code:
def blackCount(p):
    if p == "#":
        return 1
    else:
        return 0


def dfs(x,y,count):
    global minValue

    # print(f'x=#{x},y=#{y}')
    if y == h or x == w:
        return 0

    count += blackCount(board[y][x])

    if y == (h-1) and x == (w-1):
        # print(f'min=#{minValue},count#{count}')
        minValue = min(minValue,count)
        return minValue

    return dfs(x+1,y,count) + dfs(x,y+1,count)

if __name__=="__main__":
    h, w = [int(x) for x in input().split()]
    board = [list(input()) for _ in range(h)]
    minValue = h + w
    dfs(0,0,0)
    print(minValue)

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, usedRC0, minFlipSize):
	
# 	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 not visited[hi-row0].any(): break
	
	if visited[h-1-row0,w-1-col0]:
# 		print("found")
		return flipSize
					
# 	print(next)
	if len(next)==0: return None
	if targetColor: nextFlipSize=flipSize+1
	else: nextFlipSize=flipSize
	
	for nrc in next:
		if nrc in usedRC0: continue
		usedRC0.add(nrc)
# 		print("mi", minFlipSize, "ne", nextFlipSize)
		
		if minFlipSize is not None and nextFlipSize>=minFlipSize: continue
		fs=travel(colors, h, w, nrc[0], nrc[1], not targetColor, nextFlipSize, usedRC0, minFlipSize)
		if fs is None: continue
		if minFlipSize is None or fs<minFlipSize: minFlipSize=fs
	return min(minFlipSize, minFlipSize)
				

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.astype(np.uint8))

	usedRC0=set()
	
	if colors[0,0]: nextFlipSize=0
	else: nextFlipSize=1
	flipSize=travel(colors, h, w, 0, 0, colors[0,0], nextFlipSize, usedRC0, None)
# 	print("flipSize",flipSize)
	print(flipSize)
	

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

Submission status: Time Limit Exceeded

Solution code:
h, w = list(map(int, input().split(" ")))
matrix = []
result = []

for i in range(h):
    matrix.append(input())
    
def check(x, y, count):
  if x > (h - 1):
    return
  if y > (w - 1):
    return

  if matrix[x][y] == "#":
    if result and min(result) < count:
      return
    count += 1
  if x == (w - 1) and y == (h - 1):
    result.append(count)
  check(x+1, y, count)
  check(x, y+1, count)

check(0, 0, 0)
min_result = min(result) if result else 0
print(min_result)

Submission status: Time Limit Exceeded

Solution code:
all_paths = [[]]


def printAllPathsUtil(mat, i, j, m, n, path, pi):
    if i == m - 1:
        for k in range(j, n):
            path[pi + k - j] = mat[i][k]
        for l in range(pi + n - j):
            all_paths[len(all_paths)-1].append(path[l])
        all_paths.append([])
        return
    if j == n - 1:
        for k in range(i, m):
            path[pi + k - i] = mat[k][j]
        for l in range(pi + m - i):
            all_paths[len(all_paths)-1].append(path[l])
        all_paths.append([])
        return
    path[pi] = mat[i][j]
    printAllPathsUtil(mat, i + 1, j, m, n, path, pi + 1)
    printAllPathsUtil(mat, i, j + 1, m, n, path, pi + 1)


def printAllPaths(mat, m, n):
    path = [0 for i in range(m + n)]
    printAllPathsUtil(mat, 0, 0, m, n, path, 0)


h, w = map(int, input().split())
mat = []
for i in range(h):
    mat.append(list(input()))
printAllPaths(mat, h, w)
answer = pow(10, 9)
all_paths.pop()
for i in all_paths:
    answer = min(i.count('#'), answer)
print(answer)

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_tmp = []
for i in range(h):
    tmp = []
    for j in range(w):
        tmp.append(s[i][j])
    t_tmp.append(tmp)


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

# スタートを設定してsをコピー
t = copy.deepcopy(t_tmp)
#print(t)
tmp_list = []
while q:
    #print(q)
    x,y,c = q.popleft()
    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] == '.':
            t[nx][ny] = '#'
            q.append((nx,ny,c))
            pass_ = 1
            if (nx+1,ny+2) == (h, w):
                if t[nx][ny+1] == '.':
                    tmp_list.append(c)
                elif t[nx][ny+1] == '#':
                    tmp_list.append(c+1)
            elif (nx+2,ny+1) == (h, w):
                if t[nx+1][ny] == '.':
                    tmp_list.append(c)
                elif t[nx+1][ny] == '#':
                    tmp_list.append(c+1)

    if pass_ == 0:
        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] == '#':
                t[nx][ny] = '#'
                q.append((nx,ny,c+1))
                
                if (nx+1,ny+2) == (h, w):
                    if t[nx][ny+1] == '.':
                        tmp_list.append(c+1)
                    elif t[nx][ny+1] == '#':
                        tmp_list.append(c+2)

                elif (nx+2,ny+1) == (h, w):
                    if t[nx+1][ny] == '.':
                        tmp_list.append(c+1)
                    elif t[nx+1][ny] == '#':
                        tmp_list.append(c+2)
if tmp_list == []:
    print('0')
else:
    print(min(tmp_list))

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
H,W=map(int,input().split())
S=[list(input()) for i in range(H)]
now='.'
ans=0
x,y=0,0
if S[x][y]=='#':
  ans+=1
  now='#'
  
def findroot(x,y):
  global nextkouho,now,S
  nextkouho.add((x,y))
  if x<H-1 and S[x+1][y]==now:
    findroot(x+1,y)
  if y<W-1 and S[x][y+1]==now:
    findroot(x,y+1)
kouho=[(0,0)]
while 1:
  nextkouho=set()
  for x,y in kouho:
    if x<H-1 and S[x+1][y]==now:
      findroot(x+1,y)
    else:
      nextkouho.add((x,y))
    if y<W-1 and S[x][y+1]==now:
      findroot(x,y+1)
    else:
      nextkouho.add((x,y))
  if (H-1,W-1) in nextkouho:
    break
  if now=='#':
    now='.'
  else:
    ans+=1
    now='#'
  kouho=nextkouho
  #print(nextkouho,kouho,now,ans)
print(ans)

Submission status: Time Limit Exceeded

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

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

def permutations(L):
    
    if L == []:
        return [[]]

    else:
        ret = []

        # set（集合）型で重複を削除、ソート
        S = sorted(set(L))

        for i in S:

            data = L[:]
            data.remove(i)

            for j in permutations(data):
                ret.append([i] + j)

        return ret
        
junretsu = permutations([0]*W+[1]*H)

ans=10**10
for i in junretsu:
    h=0
    w=0
    now=0
    for g in i:
        if g==0:
            w+=1
            if c[h][w]=="#":
                now+=1
        if g==1:
            h+=1
            if c[h][w]=="#":
                now+=1
    ans=min(ans,now)

if c[0][0]=="#":
    ans+=1

print(ans)

Submission status: Time Limit Exceeded

Solution code:

def ans_dp(H,W,M):
    dp = [[0 for i in range(H*W)] for j in range(H*W)]
    flag = [[0 for i in range(H*W)] for j in range(H*W)]
    if M[0][0] == "#":
        dp[0][0] = 1
        flag[0][0] = 1
    else:
        dp[0][0] == 0
    for i in range(1,W):
        if M[0][i] == "#":
            flag[0][i] = 1
            if flag[0][i-1] == 1:
                dp[0][i] = dp[0][i-1]
            else:
                dp[0][i] = dp[0][i-1] + 1 
        else:##M[0][i] = "."
            dp[0][i] = dp[0][i-1]
    for j in range(1,H):
        if M[j][0] == "#":
            flag[j][0] = 1
            if flag[j-1][0] == 1:
                dp[j][0] = dp[j-1][0]
            else:
                dp[j][0] = dp[j-1][0] + 1 
        else:##M[0][i] = "."
            dp[j][0] = dp[j-1][0]
    
    for i in range(1,H):
        for j in range(1,W):
            if M[i][j] == "#":
                flag[i][j] = 1
                dp[i][j] = min(dp[i-1][j]+int(not flag[i-1][j]),dp[i][j-1]+int(not flag[i][j-1]))
            else:#M[i][j] == "."
                dp[i][j] = min(dp[i-1][j],dp[i][j-1])
    """
    for i in range(H):
        print(dp[i])
    for i in range(H):
        print(flag[i])
    """
    return dp[W-1][H-1]

def main():
    H,W = map(int,input().split())
    M = []
    for i in range(H):
        M.append(list(input()))
    print(ans_dp(H,W,M))
 
if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
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:
from collections import deque
INF = int(1e9) + 7
h, w = map(int, input().split())
s = [list(input()) for i in range(h)]
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:
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

M = [g(m) for m in range(1,W+1,1)]

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

N = [g(n) for n in range(1,H+1,1)]
  
def f(n,m):
  if n == 1:
    return M[m-1]
  elif m == 1:
    return N[n-1]
  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:
import itertools
h, w = map(int, input().split())
m = [list(map(str, input().split())) for i in range(h)]

l = []
for _ in range(1, h):
    l.append(True)
for _ in range(1, w):
    l.append(False)

p = set(itertools.permutations(l))

mn = 100 ** 2
for i in p:
    count = 0
    s = 0
    t = 0
    for j in i:
        if j:
            s += 1
            if m[s][0][t] == "#":
                count += 1
        else:
            t += 1
            if m[s][0][t] == "#":
                count += 1
    mn = min(mn, count)

if m[0][0][0] == "#":
    mn += 1

print(mn)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

#スタート位置、ゴール位置の指定がある場合
def bfs():
    #移動距離　最小値に更新していく
    d = [[float("inf")] * C for _ in range(R)]

    dx = [1,0]
    dy = [0,1]
    que = deque([])
    que.append((sy, sx))
    if maze[sy][sx] == ".":
        d[sy][sx] = 0
    else:
        d[sy][sx] = 1
 

    while que:
        p = que.popleft()
        if p[0] == gy and p[1] == gx:
            break

        for i in range(2):
            nx = p[1] + dx[i]
            ny = p[0] + dy[i]

            if 0<=nx<C and 0<=ny<R:
                #全周を超えない
                que.append((ny, nx))
                if maze[p[0]][p[1]] != maze[ny][nx] and maze[p[0]][p[1]] == ".":
                    d[ny][nx] = min(d[ny][nx], d[p[0]][p[1]] + 1)
                else:
                    d[ny][nx] = min(d[ny][nx], d[p[0]][p[1]])

    return d[gy][gx]

R,C = map(int,input().split())
sy, sx = 0,0
gy, gx = R-1,C-1

maze = [list(input()) for _ in range(R)]

print(bfs())

Submission status: Time Limit Exceeded

Solution code:
h, w = list(map(int, input().split(" ")))
matrix = []
result = []

for i in range(h):
    matrix.append(input())
    
def check(x, y, count):
  if x > (h - 1):
    return
  if y > (w - 1):
    return

  if matrix[x][y] == "#":
    count += 1
  if x == (w - 1) and y == (h - 1):
    result.append(count)
  check(x+1, y, count)
  check(x, y+1, count)

check(0, 0, 0)
min_result = min(result) if result else 0
print(min_result)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
h,w = map(int,input().split())
l = [list(input()) for i in range(h)]

dp = [[[-1]*(h*w) for i in range(w)] for i in range(h)]
q = deque([])
if l[0][0] == ".":
    q.append((0,0,0,"."))
else:
    q.append((0,0,1,"#"))
dx = [0,1]
dy = [1,0]
while q:
    
    bx,by,num,bef = q.popleft()
    for j in range(2):
        nx = bx+dx[j]
        ny = by+dy[j]
        if nx < h and ny < w:
            if bef == "." and l[nx][ny] == "#":
                if dp[nx][ny][num+1] == -1:
                
                    dp[nx][ny][num+1] = 1
                    q.append((nx,ny,num+1,l[nx][ny]))
            elif dp[nx][ny][num] == -1:
                dp[nx][ny][num] = 1
                q.append((nx,ny,num,l[nx][ny]))

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

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
H,W=map(int,input().split())
S=[list(input()) for i in range(H)]
now='.'
ans=0
x,y=0,0
if S[x][y]=='#':
  ans+=1
  now='#'
  
def findroot(x,y,S,d,now):
  global nextkouho
  nextkouho.add((x,y))
  if x<H-1 and S[x+1][y]==now:
    findroot(x+1,y,S,d+1,now)
  if y<W-1 and S[x][y+1]==now:
    findroot(x,y+1,S,d+1,now)
kouho=[(0,0)]
while 1:
  nextkouho=set()
  for x,y in kouho:
    if x<H-1 and S[x+1][y]==now:
      findroot(x+1,y,S,0,now)
    else:
      nextkouho.add((x,y))
    if y<W-1 and S[x][y+1]==now:
      findroot(x,y+1,S,0,now)
    else:
      nextkouho.add((x,y))
  if (H-1,W-1) in nextkouho:
    break
  if now=='#':
    now='.'
  else:
    ans+=1
    now='#'
  kouho=list(nextkouho)
  #print(nextkouho,kouho,now,ans)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np

h, w = map(int, input().split())

def to_num(input_str):
    if input_str == '.':
        return 0
    else:
        return 1

matrix = []
for i in range(h):
    matrix.append(list(map(to_num, list(input()))))

matrix = np.array(matrix)

def check_right_down(check_list):
    if check_list.shape[0] == 1 or check_list.shape[1] == 1:
        return np.sum(check_list)
    else:
        return min(check_right_down(check_list[1:,:]), check_right_down(check_list[:,1:])) + check_list[0, 0]

print(check_right_down(matrix))

Submission status: Time Limit Exceeded

Solution code:
H,W = map(int, input().split())
S = []
for h in range(H):
    tmp_Si = input()
    Si = []
    for w in range(W):
        if tmp_Si[w] == '.':  #白
            Si.append(0)
        else:   #黒
            Si.append(1)
    S.append(Si)

#print(S)
move_vec = [[0,1], [1,0]]
record = []

def move_and_record(h, w, black):
    for dh, dw in move_vec:
        nh = h + dh
        nw = w + dw
        #print('nh=',nh)
        #print('nw=',nw)
        if nh == H-1 and nw == W-1: #ゴール
            if S[nh][nw] == 1:
                black += 1
            else:   #S[nh][nw] == 0:
                pass
            record.append(black)
        elif nh > H-1: #もう下にはいけない
            pass
        elif nw > W-1: #もう右にはいけない
            pass
        else:   #さらに進む
            if S[nh][nw] == 1:
                move_and_record(nh, nw, black+1)
            else:   #S[nh][nw] == 0:
                move_and_record(nh, nw, black)

if S[0][0] == 1:
    move_and_record(0,0,1)
else:   #S[0][0] == 0:
    move_and_record(0,0,0)

#print(record)
print(min(record))

Submission status: Time Limit Exceeded

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

def permutations(L):
    
    if L == []:
        return [[]]

    else:
        ret = []

        # set（集合）型で重複を削除、ソート
        S = sorted(set(L))

        for i in S:

            data = L[:]
            data.remove(i)

            for j in permutations(data):
                ret.append([i] + j)

        return ret
        
junretsu = permutations([0]*W+[1]*H)
ans=10**10
for i in junretsu:
    h=0
    w=0
    now=0
    for g in i:
        if g==0:
            w+=1
            if c[h][w]=="#":
                now+=1
        if g==1:
            h+=1
            if c[h][w]=="#":
                now+=1
    ans=min(ans,now)

if c[0][0]=="#":
    ans+=1

print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
H,W=map(int,input().split())
S=[list(input()) for i in range(H)]
#print(S)
now='.'
ans=0
x,y=0,0
if S[x][y]=='#':
  ans+=1
  now='#'
  
def findroot(x,y,S,d,now,nextkouho):
  nextkouho.add((x,y))
  if x<H-1 and S[x+1][y]==now:
    nextkouho=findroot(x+1,y,S,d+1,now,nextkouho)
  if y<W-1 and S[x][y+1]==now:
    nextkouho=findroot(x,y+1,S,d+1,now,nextkouho)
  return nextkouho
kouho=[(0,0)]
#print(kouho)
while 1:
  nextkouho=set()
  for x,y in kouho:
    if x<H-1 and S[x+1][y]==now:
      nextkouho=findroot(x+1,y,S,0,now,nextkouho)
    else:
      nextkouho.add((x,y))
    if y<W-1 and S[x][y+1]==now:
      nextkouho=findroot(x,y+1,S,0,now,nextkouho)
    else:
      nextkouho.add((x,y))
  if (H-1,W-1) in nextkouho:
    break
  if now=='#':
    now='.'
  else:
    ans+=1
    now='#'
  kouho=list(nextkouho)
  #print(nextkouho,kouho,now,ans)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import itertools
h, w = map(int, input().split())
m = [list(map(str, input().split())) for i in range(h)]

l = []
for _ in range(1, h):
    l.append(True)
for _ in range(1, w):
    l.append(False)

p = set(itertools.permutations(l))

mn = 100 ** 2
for i in p:
    r = []
    s = 0
    t = 0
    for j in i:
        if j:
            s += 1
            r.append(m[s][0][t])
        else:
            t += 1
            r.append(m[s][0][t])
    mn = min(mn, r.count("#"))

if m[0][0][0] == "#":
    mn += 1

print(mn)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

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

def next_positions(current_position):
    output = []
    for udrl in [[0,1],[1,0]]:
        y = current_position[0]+udrl[0]
        x = current_position[1]+udrl[1]
        if 0 <= y <= H-1 and 0 <= x <= W-1:
            output.append([y,x,s[y][x]])
    if len(output) == 2:
        if output[0][2] == current_position[2] and output[1][2] != current_position[2]:
            del output[1]
        elif output[0][2] != current_position[2] and output[1][2] == current_position[2]:
            del output[0]
    return output

d = deque([[0,0,s[0][0]]])
distance = [[float("inf")]*W for _ in range(H)]
if s[0][0] == ".":
    distance[0][0] = 0
else:
    distance[0][0] = 1

while d:
    current_position = d.popleft()
    for q in next_positions(current_position):
        if s[int(q[0])][int(q[1])] == s[0][0] and current_position[2] != s[0][0]:
            distance[int(q[0])][int(q[1])] = min(distance[int(q[0])][int(q[1])], distance[current_position[0]][current_position[1]] + 1)
        else:
            distance[int(q[0])][int(q[1])] = min(distance[int(q[0])][int(q[1])], distance[current_position[0]][current_position[1]])
        d.append(q)

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

Submission status: Time Limit Exceeded

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

is_white = True
st = []
st.append([False, 0, 0, 0])
min_cnt = 1000

while st:
    is_prev_black, cnt, ph, pw = st.pop()
    
    is_now_black = True
    if s[ph][pw] == ".":
        is_now_black = False

    if not is_prev_black and is_now_black:
        cnt += 1

    if ph == H-1 and pw == W-1:
        min_cnt = min(min_cnt, cnt)

    if ph+1 < H:
        st.append([is_now_black, cnt, ph+1, pw])
    if pw+1 < W:
        st.append([is_now_black, cnt, ph, pw+1])

print(min_cnt)

Submission status: Time Limit Exceeded

Solution code:
input = raw_input
h, w = map(int, input().split(" "))
gh = h - 1
gw = w - 1

#dot_coords = []
#for hi in range(h):
#    wi = 0
#    for c in input():
#        if c == ".":
#            dot_coords.append((wi, hi))
#        wi += 1
        
maps = [input() for _ in range(h)]
num_maps = [[None for _ in range(w)] for _ in range(h)]

count = 0
next_cost_coord = []
def find(sx, sy, cur_cost):
    num_r = 1
    found = False
    routes = [(sx, sy)]
    num_maps[sy][sx] = cur_cost

    pre = False
    if sx == 1 and sy == 1:
        pre = True

    while num_r >= 1 and not found:
        x, y = routes[0]
        routes = routes[1:]
        num_r -= 1

        for nx, ny in [(x+1, y), (x, y+1)]:
            if pre:
                pass
                #print("lennummap", len(num_maps))
                #print(num_maps, ny, nx)
                #print(x, y, nx, ny, num_maps[ny][nx], gw, gh, "routes", routes)

            if nx <= gw and ny <= gh and num_maps[ny][nx] is None:
                #print(x, y, nx, ny, num_maps[ny][nx], gw, gh, "routes", routes)
                #print("nxny", nx, ny, cur_cost)
                if maps[ny][nx] == ".":
                    num_maps[ny][nx] = cur_cost
                    if nx == gw and ny == gh:
                        found = True
                    else:
                        routes.append((nx, ny))
                        num_r += 1
                else:
                    next_cost_coord.append((nx, ny))
    return next_cost_coord, found

cur_coords = [(0, 0)]
if maps[0][0] == ".":
    cur_cost = 0
else:
    cur_cost = 1

while True:   
    #print("cur_cost", cur_cost, "cur_coords", cur_coords)
    next_coords = []
    for sx, sy in cur_coords:
        cur_nc_coord, found = find(sx, sy, cur_cost)
        next_coords += cur_nc_coord
        #print(cur_nc_coord)
        found = num_maps[gh][gw] is not None
        if found:
            break
    #print("cur_cost", cur_cost,"num_maps", num_maps)
    if found:
        break
    else:
        #print("test")
        cur_coords = next_coords
        assert len(cur_coords) >= 1
        cur_cost += 1
        #print("cur_cost", cur_cost)

out = num_maps[gh][gw]
print(out)

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, usedRC0: set):
# 	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 not visited[hi-row0].any(): break
	
	if visited[h-1-row0,w-1-col0]:
# 		print("found")
# 		return flipSize
		print(flipSize)
		sys.exit(0)
					
# 	print("next",next)
	if len(next)==0: return None
	minFlipSize=None
	if targetColor: nextFlipSize=flipSize+1
	else: nextFlipSize=flipSize
	for nrc in next:
		if nrc in usedRC0: continue
		usedRC0.add(nrc)
		p=(colors, h, w, nrc[0], nrc[1], 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.astype(np.int32))
	
	if colors[0,0]: nextFlipSize=0
	else: nextFlipSize=1
	
	nextParams=deque()
	p=(colors, h, w, 0, 0, colors[0,0], nextFlipSize)
	nextParams.append(p)
	
	usedRC0=set()
	while len(nextParams)>0:
		param=nextParams.popleft()
		travel(*param, nextParams=nextParams, usedRC0=usedRC0)
# 	print("flipSize",flipSize)
# 	print(flipSize)
	

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

Submission status: Time Limit Exceeded

Solution code:
import itertools
h, w = map(int, input().split())
m = [list(map(str, input().split())) for i in range(h)]

l = []
for _ in range(1, h):
    l.append(True)
for _ in range(1, w):
    l.append(False)

p = list(itertools.permutations(l))

mn = 100 ** 2
for i in p:
    r = []
    s = 0
    t = 0
    for j in i:
        if j:
            s += 1
            r.append(m[s][0][t])
        else:
            t += 1
            r.append(m[s][0][t])
    mn = min(mn, r.count("#"))

if m[0][0][0] == "#":
    mn += 1

print(mn)

Submission status: Time Limit Exceeded

Solution code:
def solve(l, i, j):
	if i==0 and j==0:
		if l[0][0]=='#':
			return 1
		else:
			return 0
	else:
		if l[i][j]=='#':
			if(i==0):
				return(solve(l, i, j-1)+1)
			if(j==0):
				return(solve(l, i-1, j)+1)
			else:
				return(min(solve(l, i-1, j), solve(l, i, j-1))+1)
		else:
			if(i==0):
				return(solve(l, i, j-1))
			if(j==0):
				return(solve(l, i-1, j))
			else:
				return(min(solve(l, i-1, j), solve(l, i, j-1)))
from sys import stdin, stdout
h, w = stdin.readline().split()
h = int(h)
w = int(w)
l = [list(input()) for x in range(h)]
print(solve(l, h-1, w-1))

Submission status: Time Limit Exceeded

Solution code:
import itertools

H, W = map(int, input().split())
s = [""] * H
for i in range(H):
  s[i] = input()

res = H*W
induce = ["r"]*(H-1) + ["c"]*(W-1)
M = len(induce)
perm_iter = itertools.permutations(induce)
for i, perm in enumerate(perm_iter):
  route = ""
  r, c = 0, 0
  route += s[0][0]
  for j in range(M):
    if perm[j] == "r":
      r += 1
    elif perm[j] == "c":
      c += 1
    route += s[r][c]
  
  cnt = route.split(".")
  cnt = len(cnt) - cnt.count("")
  if cnt < res:
    res = cnt
  
print(res)

Submission status: Time Limit Exceeded

Solution code:
h,w=map(int,input().split())
s=[list(input()) for _ in range(h)]
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-1 and y==h-1:
        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])