Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import sys
- from collections import deque
- class point:
- def __init__(self, x, y):
- self.x = x
- self.y = y
- def isvalid(self, n, m):
- if self.x >= 0 and self.x < n and self.y>=0 and self.y<m:
- return True
- return False
- def __eq__(self, pnt):
- if self.x == pnt.x and self.y==pnt.y:
- return True
- return False
- def valid_points(pnt, n, m):
- rv = []
- for i in [ [-1, 0], [1, 0], [0, 1], [0, -1]]:
- pt = point(pnt.x + i[0], pnt.y + i[1])
- if pt.isvalid(n, m):
- rv.append(pt)
- def dfs_util(dp, graph, n, m, G, pnt):
- if G ==pnt:
- return 1
- for pt in valid_points(pnt, n, m):
- adder = 1
- if graph[pt.x][pt.y] == '#':
- adder = graph[pnt.x][pnt.y][1]
- dp[pt.x][pt.y][0] = min(dp[pt.x][pt.y][0], dp[pnt.x][pnt.y][0] + adder)
- dp[pt.x][pt.y][1] = dp[pnt.x][pnt.y][1] + int(graph[pt.x][pt.y] == '#')
- def solve(n, m, graph):
- dp = [ [[(n*m)**2, 0] for j in range(m)] for i in range(n) ]
- S = point(-1, -1)
- found = False
- for i in range(n):
- for j in range(m):
- if graph[i][j] =='S':
- S = point(i, j)
- found=True
- break
- if found:
- break
- G = point(-1, -1)
- found = False
- for i in range(n):
- for j in range(m):
- if graph[i][j] =='G':
- G = point(i, j)
- found=True
- break
- if found:
- break
- dp[S.x][S.y] = 0
- dfs_util(dp, graph, n, m, G, S)
- return dp[G.x][G.y]
- def main(lines):
- # このコードは標準入力と標準出力を用いたサンプルコードです。
- # このコードは好きなように編集・削除してもらって構いません。
- # ---
- # This is a sample code to use stdin and stdout.
- # Edit and remove this code as you like.
- n, m = map(int, lines[0].strip().split(' '))
- graph = lines[1:n+1]
- print(solve(n, m, graph))
- if __name__ == '__main__':
- lines = []
- for l in sys.stdin:
- lines.append(l.rstrip('\r\n'))
- main(lines)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement