Advertisement
dark-Matter

Untitled

Oct 17th, 2020
301
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.19 KB | None | 0 0
  1. import sys
  2. from collections import deque
  3.  
  4. class point:
  5.     def __init__(self, x, y):
  6.         self.x = x
  7.         self.y = y
  8.     def isvalid(self, n, m):
  9.         if self.x >= 0 and self.x < n and self.y>=0 and self.y<m:
  10.             return True
  11.         return False
  12.     def __eq__(self, pnt):
  13.         if self.x == pnt.x and self.y==pnt.y:
  14.             return True
  15.         return False
  16.  
  17. def valid_points(pnt, n, m):
  18.     rv = []
  19.     for i in [ [-1, 0], [1, 0], [0, 1], [0, -1]]:
  20.         pt = point(pnt.x + i[0], pnt.y + i[1])
  21.         if pt.isvalid(n, m):
  22.             rv.append(pt)
  23.  
  24. def dfs_util(dp, graph, n, m, G, pnt):
  25.     if G ==pnt:
  26.         return 1
  27.     for pt in valid_points(pnt, n, m):
  28.         adder = 1
  29.         if graph[pt.x][pt.y] == '#':
  30.             adder = graph[pnt.x][pnt.y][1]
  31.         dp[pt.x][pt.y][0] = min(dp[pt.x][pt.y][0], dp[pnt.x][pnt.y][0] + adder)
  32.         dp[pt.x][pt.y][1] = dp[pnt.x][pnt.y][1] + int(graph[pt.x][pt.y] == '#')
  33.  
  34.  
  35. def solve(n, m, graph):
  36.     dp = [ [[(n*m)**2, 0] for j in range(m)] for i in range(n) ]
  37.     S = point(-1, -1)
  38.     found = False
  39.     for i in range(n):
  40.         for j in range(m):
  41.             if graph[i][j] =='S':
  42.                 S = point(i, j)
  43.                 found=True
  44.                 break
  45.         if found:
  46.             break
  47.    
  48.     G = point(-1, -1)
  49.     found = False
  50.     for i in range(n):
  51.         for j in range(m):
  52.             if graph[i][j] =='G':
  53.                 G = point(i, j)
  54.                 found=True
  55.                 break
  56.         if found:
  57.             break
  58.    
  59.     dp[S.x][S.y] = 0
  60.  
  61.     dfs_util(dp, graph, n, m, G, S)
  62.  
  63.     return dp[G.x][G.y]
  64.  
  65.    
  66.  
  67. def main(lines):
  68.     # このコードは標準入力と標準出力を用いたサンプルコードです。
  69.     # このコードは好きなように編集・削除してもらって構いません。
  70.     # ---
  71.     # This is a sample code to use stdin and stdout.
  72.     # Edit and remove this code as you like.
  73.  
  74.     n, m = map(int, lines[0].strip().split(' '))
  75.     graph = lines[1:n+1]
  76.     print(solve(n, m, graph))
  77.  
  78.  
  79. if __name__ == '__main__':
  80.     lines = []
  81.     for l in sys.stdin:
  82.         lines.append(l.rstrip('\r\n'))
  83.     main(lines)
  84.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement