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: Accepted

Solution code:
from itertools import product
from heapq import heappush, heappop

class Dijkstra:
    def __init__(self, N):
        self.N = N # #vertices
        self.E = [[] for _ in range(N)]

    def add_edge(self, init, end, weight, undirected=False):
        self.E[init].append((end, weight))
        if undirected: self.E[end].append((init, weight))
    
    def distance(self, s):
        INF = float('inf')
        self.dist = [INF] * self.N # the distance of each vertex from s
        self.prev = [-1] * self.N # the previous vertex of each vertex on a shortest path from s
        n_visited = 0 # #(visited vertices)
        heap = []
        heappush(heap, (0, -1, s))
        while heap:
            d, p, v = heappop(heap)
            if self.dist[v] != INF: continue # (s,v)-shortest path is already calculated
            self.dist[v] = d; self.prev[v] = p
            n_visited += 1
            if n_visited == self.N: break
            for u, c in self.E[v]:
                if self.dist[u] != INF: continue
                temp = d + c
                if self.dist[u] > temp: heappush(heap, (temp, v, u))
        return self.dist
    
    def shortest_path(self, t):
        P = []
        prev = self.prev
        while True:
            P.append(t)
            t = prev[t]
            if t == -1: break
        return P[::-1]

H, W = map(int, input().split())
dijkstra = Dijkstra(H * W)

def vtx(i, j): return i*W + j
def coord(n): return divmod(n, W)

grid = [input() for _ in range(H)] # |string| = W
E = [[] for _ in range(H * W)]
ans = 0 if grid[0][0] == '.' else 1
for i, j in product(range(H), range(W)):
    v = vtx(i, j)
    check = [vtx(i+dx, j+dy) for dx, dy in [(1, 0), (0, 1)] if i+dx <= H-1 and j+dy <= W-1]
    for u in check:
        x, y = coord(u)
        if grid[i][j] == '.' and grid[x][y] == '#':
            dijkstra.add_edge(v, u, 1)
        else:
            dijkstra.add_edge(v, u, 0)
dist = dijkstra.distance(0)
ans += dist[vtx(H-1, W-1)]
print(ans)

Submission status: Accepted

Solution code:
from itertools import product

class BellmanFord:
    def __init__(self, N):
        self.N = N # #vertices
        self.E = [[] for _ in range(N)]

    def add_edge(self, init, end, weight, undirected=False):
        self.E[init].append((end, weight))
        if undirected: self.E[end].append((init, weight))
    
    def distance(self, s):
        INF = float('inf')
        self.dist = [INF] * self.N # the distance of each vertex from s
        self.prev = [-1] * self.N # the previous vertex of each vertex on a shortest path from s
        self.dist[s] = 0
        for _ in range(self.N):
            updated = False
            for v in range(self.N):
                d = self.dist[v]
                if d == INF: continue
                for u, c in self.E[v]:
                    temp = d + c
                    if self.dist[u] > temp:
                        updated = True
                        self.dist[u] = temp
                        self.prev[u] = v
            if not updated: break # the minimum costs are already stored in dist
        else: return None # the above loop is not broken if and only if there exists a negative cycle
        return self.dist
    
    def shortest_path(self, t):
        P = []
        prev = self.prev
        while True:
            P.append(t)
            t = prev[t]
            if t == -1: break
        return P[::-1]

H, W = map(int, input().split())
bf = BellmanFord(H * W)

def vtx(i, j): return i*W + j
def coord(n): return divmod(n, W)

grid = [input() for _ in range(H)] # |string| = W
E = [[] for _ in range(H * W)]
ans = 0 if grid[0][0] == '.' else 1
for i, j in product(range(H), range(W)):
    v = vtx(i, j)
    check = [vtx(i+dx, j+dy) for dx, dy in [(1, 0), (0, 1)] if i+dx <= H-1 and j+dy <= W-1]
    for u in check:
        x, y = coord(u)
        if grid[i][j] == '.' and grid[x][y] == '#':
            bf.add_edge(v, u, 1)
        else:
            bf.add_edge(v, u, 0)
dist = bf.distance(0)
ans += dist[vtx(H-1, W-1)]
print(ans)

Submission status: Accepted

Solution code:
from itertools import product

class BellmanFord:
    def __init__(self, N):
        self.N = N # #vertices
        self.E = [[] for _ in range(N)]

    def add_edge(self, init, end, weight, undirected=False):
        self.E[init].append((end, weight))
        if undirected: self.E[end].append((init, weight))
    
    def distance(self, s):
        INF = float('inf')
        self.dist = [INF] * self.N # the distance of each vertex from s
        self.prev = [-1] * self.N # the previous vertex of each vertex on a shortest path from s
        self.dist[s] = 0
        for _ in range(self.N):
            updated = False
            for v in range(self.N):
                d = self.dist[v]
                if d != INF:
                    for u, c in self.E[v]:
                        temp = d + c
                        if self.dist[u] > temp:
                            updated = True
                            self.dist[u] = temp
                            self.prev[u] = v
            if not updated: break # the minimum costs are already stored in dist
        else: return None # the above loop is not broken if and only if there exists a negative cycle
        return self.dist
    
    def shortest_path(self, t):
        P = []
        prev = self.prev
        while True:
            P.append(t)
            t = prev[t]
            if t == -1: break
        return P[::-1]

H, W = map(int, input().split())
bf = BellmanFord(H * W)

def vtx(i, j): return i*W + j
def coord(n): return divmod(n, W)

grid = [input() for _ in range(H)] # |string| = W
E = [[] for _ in range(H * W)]
ans = 0 if grid[0][0] == '.' else 1
for i, j in product(range(H), range(W)):
    v = vtx(i, j)
    check = [vtx(i+dx, j+dy) for dx, dy in [(1, 0), (0, 1)] if i+dx <= H-1 and j+dy <= W-1]
    for u in check:
        x, y = coord(u)
        if grid[i][j] == '.' and grid[x][y] == '#':
            bf.add_edge(v, u, 1)
        else:
            bf.add_edge(v, u, 0)
dist = bf.distance(0)
ans += dist[vtx(H-1, W-1)]
print(ans)

Submission status: Accepted

Solution code:
from itertools import product
from collections import deque

class ZeroOneBFS:
    def __init__(self, N):
        self.N = N # #vertices
        self.E = [[] for _ in range(N)]
        
    def add_edge(self, init, end, weight, undirected=False):
        assert weight in [0, 1]
        self.E[init].append((end, weight))
        if undirected: self.E[end].append((init, weight))
        
    def distance(self, s):
        INF = float('inf')
        self.dist = [INF] * self.N # the distance of each vertex from s
        self.prev = [-1] * self.N # the previous vertex of each vertex on a shortest path from s
        visited = [False] * self.N
        dq = deque([(0, -1, s)]) # (dist, prev, vertex)
        n_visited = 0 # #(visited vertices)
        while dq:
            d, p, v = dq.popleft()
            if visited[v]: continue # (s,v)-shortest path is already calculated
            self.dist[v] = d; self.prev[v] = p; visited[v] = True
            n_visited += 1
            if n_visited == self.N: break
            for u, c in self.E[v]:
                if visited[u]: continue
                if c == 0: dq.appendleft((d, v, u))
                else: dq.append((d + 1, v, u))
        return self.dist
    
    def shortest_path(self, t):
        P = []
        prev = self.prev
        while True:
            P.append(t)
            t = prev[t]
            if t == -1: break
        return P[::-1]

H, W = map(int, input().split())
zobfs = ZeroOneBFS(H * W)
 
def vtx(i, j): return i*W + j
def coord(n): return divmod(n, W)
 
grid = [input() for _ in range(H)] # |string| = W
E = [[] for _ in range(H * W)]
ans = 0 if grid[0][0] == '.' else 1
for i, j in product(range(H), range(W)):
    v = vtx(i, j)
    check = [vtx(i+dx, j+dy) for dx, dy in [(1, 0), (0, 1)] if i+dx <= H-1 and j+dy <= W-1]
    for u in check:
        x, y = coord(u)
        if grid[i][j] == '.' and grid[x][y] == '#':
            zobfs.add_edge(v, u, 1)
        else:
            zobfs.add_edge(v, u, 0)
dist = zobfs.distance(0)
ans += dist[vtx(H-1, W-1)]
print(ans)

Submission status: Accepted

Solution code:
from itertools import product
from heapq import heappush, heappop

class Dijkstra:
    def __init__(self, N):
        self.N = N # #vertices
        self.E = [[] for _ in range(N)]

    def add_edge(self, init, end, weight, undirected=False):
        self.E[init].append((end, weight))
        if undirected: self.E[end].append((init, weight))
    
    def distance(self, s):
        INF = float('inf')
        self.dist = [INF] * self.N # the distance of each vertex from s
        self.prev = [-1] * self.N # the previous vertex of each vertex on a shortest path from s
        visited = [False] * self.N
        n_visited = 0 # #(visited vertices)
        heap = []
        heappush(heap, (0, -1, s))
        while heap:
            d, p, v = heappop(heap)
            if visited[v]: continue # (s,v)-shortest path is already calculated
            self.dist[v] = d; self.prev[v] = p; visited[v] = True
            n_visited += 1
            if n_visited == self.N: break
            for u, c in self.E[v]:
                if visited[u]: continue
                temp = d + c
                if self.dist[u] > temp: heappush(heap, (temp, v, u))
        return self.dist
    
    def shortest_path(self, t):
        P = []
        prev = self.prev
        while True:
            P.append(t)
            t = prev[t]
            if t == -1: break
        return P[::-1]

H, W = map(int, input().split())
dijkstra = Dijkstra(H * W)

def vtx(i, j): return i*W + j
def coord(n): return divmod(n, W)

grid = [input() for _ in range(H)] # |string| = W
E = [[] for _ in range(H * W)]
ans = 0 if grid[0][0] == '.' else 1
for i, j in product(range(H), range(W)):
    v = vtx(i, j)
    check = [vtx(i+dx, j+dy) for dx, dy in [(1, 0), (0, 1)] if i+dx <= H-1 and j+dy <= W-1]
    for u in check:
        x, y = coord(u)
        if grid[i][j] == '.' and grid[x][y] == '#':
            dijkstra.add_edge(v, u, 1)
        else:
            dijkstra.add_edge(v, u, 0)
dist = dijkstra.distance(0)
ans += dist[vtx(H-1, W-1)]
print(ans)

Submission status: Accepted

Solution code:
from itertools import product
from heapq import heappush, heappop

class Dijkstra:
    def __init__(self, N):
        self.N = N # #vertices
        self.E = [[] for _ in range(N)]

    def add_edge(self, init, end, weight, undirected=False):
        self.E[init].append((end, weight))
        if undirected: self.E[end].append((init, weight))
    
    def distance(self, s):
        INF = float('inf')
        self.dist = [INF] * self.N # the distance of each vertex from s
        self.prev = [-1] * self.N # the previous vertex of each vertex on a shortest path from s
        rem = self.N # #(remaining vertices)
        heap = []
        heappush(heap, (0, -1, s))
        while heap and rem:
            d, p, v = heappop(heap)
            if d >= self.dist[v]: continue # (s,v)-shortest path is already calculated
            self.dist[v] = d; self.prev[v] = p
            rem -= 1
            for u, c in self.E[v]:
                temp = d + c
                if self.dist[u] > temp: heappush(heap, (temp, v, u))
        return self.dist

H, W = map(int, input().split())
dijkstra = Dijkstra(H * W)

def vtx(i, j): return i*W + j
def coord(n): return divmod(n, W)

grid = [input() for _ in range(H)] # |string| = W
E = [[] for _ in range(H * W)]
ans = 0 if grid[0][0] == '.' else 1
for i, j in product(range(H), range(W)):
    v = vtx(i, j)
    check = [vtx(i+dx, j+dy) for dx, dy in [(1, 0), (0, 1)] if i+dx <= H-1 and j+dy <= W-1]
    for u in check:
        x, y = coord(u)
        if grid[i][j] == '.' and grid[x][y] == '#':
            dijkstra.add_edge(v, u, 1)
        else:
            dijkstra.add_edge(v, u, 0)
dist = dijkstra.distance(0)
ans += dist[vtx(H-1, W-1)]
print(ans)

Submission status: Accepted

Solution code:
n,m=map(int,input().split())
s=[list(input()) for i in range(n)]
ans=[[10**9+7]*m for i in range(n)]
ans[0][0]=int(s[0][0]=='#')
for i in range(n):
    for j in range(m):
        if i>0:
            #ans[i][j]=min(ans[i][j]+ans[i-1][j]+int(s[i-1][j]=='.' and s[i][j]=='#'))
            ans[i][j]=min(ans[i][j],ans[i-1][j]+int(s[i-1][j]=='.'and s[i][j]=='#'))
        if j>0:
            ans[i][j]=min(ans[i][j],ans[i][j-1]+int(s[i][j-1]=='.' and s[i][j]=='#'))
print(ans[n-1][m-1])

Submission status: Accepted

Solution code:
from itertools import product
from collections import deque

class ZeroOneBFS:
    def __init__(self, N):
        self.N = N
        self.E = [[] for _ in range(N)]
        
    def add_edge(self, init, end, weight, undirected=False):
        assert weight in [0, 1]
        self.E[init].append((end, weight))
        if undirected: self.E[end].append((init, weight))
        
    def distance(self, s):
        self.order = [-1] * self.N # a bfs ordering of each vertex
        self.dist = [-1] * self.N # the distance of each vertex from s
        dq = deque([(s, 0)]) # (vertex, dist)
        num = 0 # current ordering
        while dq:
            v, d = dq.popleft()
            if self.order[v] < 0: # visited v for the first time
                self.order[v] = num; self.dist[v] = d
                num += 1
                for u, w in self.E[v]:
                    if self.order[u] >= 0: continue
                    if w == 0: dq.appendleft((u, d))
                    else: dq.append((u, d+1))
        return self.order, self.dist

H, W = map(int, input().split())
zobfs = ZeroOneBFS(H * W)

def vtx(i, j): return i*W + j
def coord(n): return divmod(n, W)

grid = [input() for _ in range(H)] # |string| = W
E = [[] for _ in range(H * W)]
ans = 0 if grid[0][0] == '.' else 1
for i, j in product(range(H), range(W)):
    v = vtx(i, j)
    check = [vtx(i+dx, j+dy) for dx, dy in [(1, 0), (0, 1)] if i+dx <= H-1 and j+dy <= W-1]
    for u in check:
        x, y = coord(u)
        if grid[i][j] == '.' and grid[x][y] == '#':
            zobfs.add_edge(v, u, 1)
        else:
            zobfs.add_edge(v, u, 0)
_, dist = zobfs.distance(0)
ans += dist[vtx(H-1, W-1)]
print(ans)

Submission status: Accepted

Solution code:
h,w = map(int,input().split())
s = [input() for _ in range(h)]
dp = [[float("inf") for _ in range(w)] for _ in range(h)]
dp[0][0] = 0 if s[0][0] == "." else 1 
for i in range(h):
    for j in range(w):
        if i < h-1:
            if s[i][j] == "." and s[i+1][j] == "#":
                dp[i+1][j] = min(dp[i][j]+1,dp[i+1][j])
            else:
                dp[i+1][j] = min(dp[i][j],dp[i+1][j])
        if j < w-1:
            if s[i][j] == "." and s[i][j+1] == "#":
                dp[i][j+1] = min(dp[i][j]+1,dp[i][j+1])
            else:
                dp[i][j+1] = min(dp[i][j],dp[i][j+1])
print(dp[h-1][w-1])

Submission status: Accepted

Solution code:
from itertools import product
from collections import deque

def zero_one_bfs(E, s, init=0):
    N = len(E)
    order = [-1] * N # a bfs ordering of each vertex
    dist = [-1] * N # the distance of each vertex from s
    dq = deque([(s, init)]) # (vertex, dist)
    num = 0 # current ordering
    while dq:
        v, d = dq.popleft()
        if order[v] < 0: # visited v for the first time
            order[v] = num; dist[v] = d
            num += 1
            for u, w in E[v]:
                if order[u] >= 0: continue
                if w == 0: dq.appendleft((u, d))
                else: dq.append((u, d+1))
    return order, dist

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

def vtx(i, j): return i*W + j
def coord(n): return divmod(n, W)

grid = [input() for _ in range(H)] # |string| = W
E = [[] for _ in range(H * W)]
for i, j in product(range(H), range(W)):
    v = vtx(i, j)
    check = [vtx(i+dx, j+dy) for dx, dy in [(1, 0), (0, 1)] if i+dx <= H-1 and j+dy <= W-1]
    for u in check:
        x, y = coord(u)
        if grid[i][j] == '.' and grid[x][y] == '#':
            E[v].append((u, 1))
        elif grid[i][j] == '#' and grid[x][y] == '.':
            E[v].append((u, 0))
        else:
            E[v].append((u, 0))
_, dist = zero_one_bfs(E, 0, 0 if grid[0][0] == '.' else 1)
print(dist[vtx(H-1, W-1)])

Submission status: Accepted

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

dp = list(list(float('INF') for _ in range(W)) for _ in range(H))
dp[0][0] = 1 if field[0][0] == '#' else 0

for x in range(W):
    for y in range(H):
        if y < H - 1:
            dp[y + 1][x] = min(dp[y + 1][x],
                               dp[y][x] + 1 if field[y + 1][x] == '#' and field[y][x] == '.' else dp[y][x])
        if x < W - 1:
            dp[y][x + 1] = min(dp[y][x + 1],
                               dp[y][x] + 1 if field[y][x + 1] == '#' and field[y][x] == '.' else dp[y][x])

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

Submission status: Accepted

Solution code:
def main():
    H, W = map(int, input().split())
    S = [input() for _ in range(H)]
    ans = [[float("inf")] * (W) for _ in range(H)]
    if S[0][0] == "#":
        ans[0][0] = 1
    else:
        ans[0][0] = 0
    for i in range(H):
        for j in range(W):
            tmp = ans[i][j]
            if 0 < i:
                tmp = min(tmp, ans[i-1][j] +
                          (1 if S[i-1][j] == "." and S[i][j] == "#" else 0))
            if 0 < j:
                tmp = min(tmp, ans[i][j-1] +
                          (1 if S[i][j-1] == "." and S[i][j] == "#" else 0))
            ans[i][j] = tmp
    print(ans[H-1][W-1])


if __name__ == "__main__":
    main()

Submission status: Accepted

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

dist = [[H*W for i in range(W)] for j in range(H)]

if s[0][0] == "#":
    dist[0][0] = 1
else :
    dist[0][0] = 0

for h in range(H):
    for w in range(W):
        if w + 1 < W:
            if s[h][w] == "." and s[h][w+1] == "#":
                dist[h][w+1] = min(dist[h][w+1], dist[h][w] + 1)
            else:
                dist[h][w+1] = min(dist[h][w+1], dist[h][w])
        if h + 1 < H:
            if s[h][w] == "." and s[h+1][w] == "#":
                dist[h+1][w] = min(dist[h+1][w], dist[h][w] + 1)
            else:
                dist[h+1][w] = min(dist[h+1][w], dist[h][w])

print(dist[-1][-1])

Submission status: Accepted

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

dp = [[0] * w for _ in range(h)]
if(s[0][0] == '#'):
    dp[0][0] = 1

for i in range(h):
    for j in range(w):
        if(i == 0)&(j != 0):
            dp[i][j] = dp[i][j-1] + (s[i][j-1] != s[i][j])*1
        elif(i != 0)&(j == 0):
            dp[i][j] = dp[i-1][j] + (s[i-1][j] != s[i][j])*1
        elif(i != 0)&(j != 0):
            dp[i][j] =min(dp[i][j-1] + (s[i][j-1] != s[i][j])*1,
                            dp[i-1][j] + (s[i-1][j] != s[i][j])*1)

ans = (dp[-1][-1] + 1)//2
print(ans)

Submission status: Accepted

Solution code:
import sys

stdinr = sys.stdin.readline

ns = lambda: stdinr().rstrip()
ni = lambda: int(stdinr().rstrip())
nm = lambda: map(int, stdinr().split())
nl = lambda: list(map(int, stdinr().split()))

h,w = nm()
g = [list(map(lambda s:s=='#', list(input()))) for _ in range(h)]
dp = [[h*w]*w for _ in range(h)]
dp[0][0] = g[0][0]
for i in range(h):
    for j in range(w):
        if i < h-1:
            d = dp[i][j] + (g[i][j] < g[i+1][j])
            if dp[i+1][j] > d: dp[i+1][j] = d
        if j < w-1:
            d = dp[i][j] + (g[i][j] < g[i][j+1])
            if dp[i][j+1] > d: dp[i][j+1] = d
print(dp[-1][-1])

Submission status: Accepted

Solution code:
import sys, re, os
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians
from itertools import permutations, combinations, product, accumulate
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from fractions import gcd
 
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def S_MAP(): return map(str, input().split())
def LIST(): return list(map(int, input().split()))
def S_LIST(): return list(map(str, input().split()))
 
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7

H, W = MAP()

cost = [[INF] * (W + 1) for i in range(H + 1)]

field = ["#" * (W + 1)]

for i in range(H):
    line = input()
    field.append("#" + line)

if field[1][1] == "#":
    cost[1][1] = 1
else:
    cost[1][1] = 0

for i in range(1, H + 1):
    for j in range(1, W + 1):
        if i * j == 1:
            continue
        # そのまま
        if field[i][j] == ".":
            cost[i][j] = min(cost[i-1][j], cost[i][j-1])
        else:# 今いるところが黒
            up_cost = cost[i-1][j]
            left_cost = cost[i][j-1]
            # 上が黒
            if field[i-1][j] == ".":
                up_cost += 1
            if field[i][j-1] == ".":
                left_cost += 1
            
            cost[i][j] = min(up_cost, left_cost)
print(cost[H][W])

Submission status: Accepted

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

que = deque()
alr = [[float('inf') for i in range(W)] for j in range(H)]
if s[0][0] == '.':
    alr[0][0] = 0
else:
    alr[0][0] = 1
que.append((0,0))
while que:
    h,w = que.popleft()
    if s[h][w] == '#':
        flag = True
    else:
        flag = False

    if h < H-1:
        if s[h+1][w] == '.':
            if alr[h+1][w] > alr[h][w]:
                alr[h+1][w] = alr[h][w]
                que.append((h+1,w))
        else:
            if flag:
                if alr[h+1][w] > alr[h][w]:
                    alr[h+1][w] = alr[h][w]
                    que.append((h+1,w))
            else:
                if alr[h+1][w] > alr[h][w]+1:
                    alr[h+1][w] =alr[h][w]+1
                    que.append((h+1,w))            
    if w < W-1:
        if s[h][w+1] == '.':
            if alr[h][w+1] > alr[h][w]:
                alr[h][w+1] =alr[h][w]
                que.append((h,w+1))
        else:
            if flag:
                if alr[h][w+1] > alr[h][w]:
                    alr[h][w+1] =alr[h][w]
                    que.append((h,w+1))
            else:
                if alr[h][w+1] > alr[h][w]+1:
                    que.append((h,w+1))
                    alr[h][w+1] = alr[h][w] + 1
print(alr[-1][-1])

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
H, W = [int(str) for str in input().strip().split()]
S = [input().strip() for _ in range(H)]

def cost(h, w):
    return 1 if S[h][w] == '#' else 0

inf = 100000

# init
dp = [[inf] * W for _ in range(H)]
dp[0][0] = cost(0, 0)
for w in range(1, W):
    # dp[0][w] = dp[0][w - 1] + cost(0, w)
    dp[0][w] = dp[0][w - 1] + int(S[0][w - 1] == '.' and S[0][w] == '#')

for h in range(1, H):
    # dp[h][0] = dp[h - 1][0] + cost(h, 0)
    dp[h][0] = dp[h - 1][0] + int(S[h - 1][0] == '.' and S[h][0] == '#')
    for w in range(1, W):
        # dp[h][w] =  min(dp[h][w - 1], dp[h - 1][w]) + cost(h, w)
        if S[h][w] == '.':
            dp[h][w] = min(dp[h][w - 1], dp[h - 1][w])
        else:
            dp[h][w] = min(dp[h][w - 1] + int(S[h][w - 1] == '.'), dp[h - 1][w] + int(S[h - 1][w] == '.'))

# [print(l) for l in S]
# [print(l) for l in dp]
print(dp[H - 1][W - 1])

Submission status: Accepted

Solution code:
def main():
  import sys
  input=sys.stdin.buffer.readline
  h,w=map(int,input().split())
  b,q=b'.'*w,range(w)
  for i in range(h):
    s=input()
    a=[]
    a_add=a.append
    for x,y,z,c in zip(b,b'.'+s,s,q):
      if x==46>z:c+=1
      if y==46>z:i+=1
      if i>c:i=c
      a_add(i)
    b,q=s,a
  print(i)
main()

Submission status: Accepted

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

dp = [[10**10] * w for _ in range(h)]

for i in range(h):
    for j in range(w):
        s1 = s[i][j]
        if i == 0 and j == 0:
            if s1 == '.':
                dp[i][j] = 0
            else:
                dp[i][j] = 1
        elif i == 0:
            if s1 == '#' and s[i][j-1] == '.':
                dp[i][j] = dp[i][j-1] + 1
            else:
                dp[i][j] = dp[i][j-1]
        elif j == 0:
            if s1 == '#' and s[i-1][j] == '.':
                dp[i][j] = dp[i-1][j] + 1
            else:
                dp[i][j] = dp[i-1][j]
        else:
            if s1 == '#' and s[i][j-1] == '.':
                dp[i][j] = min(dp[i][j], dp[i][j-1] + 1)
            else:
                dp[i][j] = min(dp[i][j], dp[i][j-1])
            if s1 == '#' and s[i-1][j] == '.':
                dp[i][j] = min(dp[i][j], dp[i-1][j] + 1)
            else:
                dp[i][j] = min(dp[i][j], dp[i-1][j])

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

Submission status: Accepted

Solution code:
def main():
  import sys
  input=sys.stdin.buffer.readline
  h,w=map(int,input().split())
  b,q=b'.'*w,range(w)
  for i in range(h):
    s=input()
    a=[]
    for x,y,z,c in zip(b,b'.'+s,s,q):
      c+=x==46>z
      i+=y==46>z
      if i>c:i=c
      a+=i,
    b,q=s,a
  print(i)
main()

Submission status: Accepted

Solution code:
import sys
import copy
import math
import fractions

import bisect
import pprint
import bisect
from functools import reduce
from copy import deepcopy
from collections import deque
import numpy as np
from decimal import *

maiz = []
maxh = 0
maxw = 0


def CheckCost(h, w):
    if h + 1 < maxh:
        if costList[h + 1][w] == -1 or costList[h + 1][w] > costList[h][w] + CheckColum(h + 1, w ,maiz[h][w]):
            costList[h + 1][w] = costList[h][w] + CheckColum(h + 1, w ,maiz[h][w])
            CheckCost(h + 1, w)

    if w + 1 < maxw:
        if costList[h][w + 1] == -1 or costList[h][w + 1] > costList[h][w] + CheckColum(h, w + 1,maiz[h][w]):
            costList[h][w + 1] = costList[h][w] + CheckColum(h, w + 1,maiz[h][w])
            CheckCost(h, w + 1)


def CheckColum(h, w ,s):
    if maiz[h][w] == "#" and s == ".":
        return 1
    else:
        return 0


if __name__ == '__main__':
    h, w = map(int, input().split())
    maxh = h
    maxw = w
    costList = []
    for i in range(h):
        costList.append([-1] * w)

    for i in range(h):
        s = input()
        maiz.append(list(map(lambda x: x, s)))
    if maiz[0][0] == "#":
        costList[0][0] = 1
    else:
        costList[0][0] = 0

    CheckCost(0, 0)

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

Submission status: Accepted

Solution code:
def main():
  _,*s=open(0)
  b,q='.'*101,range(101)
  for i,s in enumerate(s):
    a=[]
    for x,y,z,c in zip(b,'.'+s,s,q):
      c+=x=='.'>z
      i+=y=='.'>z
      if i>c:i=c
      a+=i,
    b,q=s,a
  print(a[-2])
main()

Submission status: Accepted

Solution code:
_,*s=open(0)
b,q='.'*101,range(101)
for i,s in enumerate(s):
  a=[i]
  for x,y,z,c in zip(b,'.'+s,s,q):a+=min(c+(x=='.'>z),a[-1]+(y=='.'>z)),
  b,q=s,a[1:]
print(a[-2])

Submission status: Accepted

Solution code:
_,*s=open(0)
b,q='.'*101,range(101)
for i,s in enumerate(s):
  a=[i]
  for x,y,z,c in zip(b,'.'+s,s,q):
    a+=min(c+(x=='.'>z),a[-1]+(y=='.'>z)),
  b,q=s,a[1:]
print(a[-2])

Submission status: Accepted

Solution code:
import numpy as np

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

dp = np.full((h+1, w+1), h+w, dtype=np.int)

for i in range(h):
    for k in range(w):
        if i == k == 0:
            dp[i+1, k+1] = 1 if grid[i, k] == '#' else 0
        else:
            if grid[i, k] == '#':
                a = dp[i, k+1] if grid[i-1, k] == '#' else dp[i, k+1] + 1
                b = dp[i+1, k] if grid[i, k-1] == '#' else dp[i+1, k] + 1
                dp[i+1, k+1] = min(a, b)
            else:
                dp[i+1, k+1] = min(dp[i, k+1], dp[i+1, k])

print(dp[h, w])

Submission status: Accepted

Solution code:
H,W=map(int,input().split())
s=[list(input()) for i in range(H)]
dp=[[10**6 for j in range(W)] for i in range(H)]
if s[0][0]=="#":
    dp[0][0]=1
else:
    dp[0][0]=0
for i in range(H):
    for j in range(W):
        if i>0:
            if (s[i][j],s[i-1][j])==("#","."):
                dp[i][j]=min(dp[i][j],dp[i-1][j]+1)
            else:
                dp[i][j]=min(dp[i][j],dp[i-1][j])
        if j>0:
            if (s[i][j],s[i][j-1])==("#","."):
                dp[i][j]=min(dp[i][j],dp[i][j-1]+1)
            else:
                dp[i][j]=min(dp[i][j],dp[i][j-1])
print(dp[-1][-1])

Submission status: Accepted

Solution code:
H, W = map(int, input().split())
s = [list(input()) for _ in range(H)]
inf = 10 ** 9
dp = [[inf] * W for _ in range(H)]
dp[0][0] = 0 if s[0][0] == '.' else 1

for y in range(H):
    for x in range(W):
        if y < H - 1:
            dp[y + 1][x] = min(dp[y + 1][x], dp[y][x] +
                               (1 if s[y][x] == '.' and s[y + 1][x] == '#' else 0))
        if x < W - 1:
            dp[y][x + 1] = min(dp[y][x + 1], dp[y][x] +
                               (1 if s[y][x] == '.' and s[y][x + 1] == '#' else 0))

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

Submission status: Accepted

Solution code:
h, w = map(int, input().split())
m = []
for i in range(h):
    inp = input()
    tmpa = inp.replace('.', '0')
    tmpb = tmpa.replace('#', '1')
    m.append(tmpb)
# print(m)

ans = [[0] * w for i in range(h)]
for y in range(h):
    for x in range(w):
        if y == 0 and x == 0:
            if m[0][0] == '1':
                ans[0][0] += 1

        elif y == 0:
            ans[y][x] = ans[y][x - 1]
            if m[y][x - 1] == '0' and m[y][x] == '1':
                ans[y][x] += 1

        elif x == 0:
            ans[y][x] = ans[y - 1][x]
            if m[y - 1][x] == '0' and m[y][x] == '1':
                ans[y][x] += 1

        else:
            ans[y][x] = min((ans[y][x - 1] + int(bool(m[y][x - 1] == '0' and m[y][x] == '1')),
                             ans[y - 1][x] + int(bool(m[y - 1][x] == '0' and m[y][x] == '1'))))
# print(ans)
print(ans[h - 1][w - 1])