Kali_prasad

find min dis with one time teleport

Dec 23rd, 2025
26
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.57 KB | None | 0 0
  1.  
  2.  
  3. '''
  4. this is an easy version
  5. where there is only portal type A
  6. in the hard version you will have multiple portal chars
  7.  
  8. you are given a matrix with empty cells(.) obstacle cells(#)
  9. and teleportation cells (A)
  10. you can use the teleportation at max 1 time
  11. in your journey ,the teleportation does not count as a move
  12. find the min moves you need to travel from 0,0 to m-1,n-1
  13.  
  14. ============================================================================================================================================
  15.  
  16. here it said you can travel through portal at max one time
  17. this is boon for us
  18.  
  19. so you just need to start multiBFS from all the teleportation points
  20. to find minDisFromStart
  21. and also another multiBFS from all teleportation points to find mindDisToEnd
  22. so just add both dis you will get the ans
  23.  
  24. but wait there is no rule to definitely use teleportation right
  25. so do a simple BFS from start to end without any teleportation
  26. and decide the final answer
  27. '''
  28. from collections import defaultdict,deque
  29. class Solution:
  30.  
  31.     def isValid(self,currx,curry,m,n):
  32.         return 0<=currx<m and 0<=curry<n
  33.  
  34.     def bfs(self,q,targetx,targety,seen,m,n,mat):
  35.         minDis = 10**10
  36.  
  37.         while len(q):
  38.             curr = q.popleft()
  39.             xaxis = [-1,0,0,1]
  40.             yaxis = [0,-1,1,0]
  41.             for i in range(4):
  42.                 currx = curr[0][0] + xaxis[i]
  43.                 curry = curr[0][1] + yaxis[i]
  44.                 if not self.isValid(currx,curry,m,n):
  45.                     continue
  46.                 if (currx,curry) in seen:
  47.                     continue
  48.                 if mat[currx][curry] == '#':
  49.                     continue
  50.                 newDis = curr[1]+1
  51.                 if currx == targetx and curry == targety:
  52.                     minDis = min(minDis,newDis)
  53.                 else:
  54.                     q.append([(currx,curry),newDis])
  55.                     seen.add((currx,curry))
  56.  
  57.         return minDis
  58.  
  59.     def calculateMindisToReachInMatrix(self,mat):
  60.         #lets grab all the teleportaion points and start a multi source BFS for start and end points
  61.         m = len(mat)
  62.         n  = len(mat[0])
  63.         q = deque()
  64.         seen = set()
  65.  
  66.         for i in range(m):
  67.             for j in range(n):
  68.                 if mat[i][j] == 'A':
  69.                     q.append([(i,j),0])
  70.                     seen.add((i,j))
  71.         minStartDis = self.bfs(q.copy(),0,0,seen.copy(),m,n,mat)
  72.         minEndDis = self.bfs(q.copy(),m-1,n-1,seen.copy(),m,n,mat)
  73.  
  74.         if mat[0][0] == 'A':
  75.             minStartDis = 0
  76.         if mat[m-1][n-1] == 'A':
  77.             minEndDis = 0
  78.  
  79.         q2 = deque()
  80.         q2.append([(0,0),0])
  81.         seen2 = set()
  82.         seen2.add((0,0))
  83.         minDirectDis = self.bfs(q2.copy(),m-1,n-1,seen2.copy(),m,n,mat)
  84.         print(f"minStartDis {minStartDis} minEndDis {minEndDis} minDirectDis {minDirectDis}")
  85.         return min(minStartDis+minEndDis,minDirectDis)#mindis with teleportation and without teleportation
  86.  
  87.  
  88. def main():
  89.     solution = Solution()
  90.    
  91.     # Test cases: (matrix, expected_min_moves, description)
  92.     test_cases = [
  93.         (
  94.             [
  95.                 ['A', '.', '.'],
  96.                 ['.', 'A', '.'],
  97.                 ['.', '.', '.']
  98.             ],
  99.             2,
  100.             "3x3 without obstacles - portal might help"
  101.         ),
  102.        
  103.          (
  104.             [
  105.                 ['.', '#', '.', '.','.'],
  106.                 ['.', '#', '.', '#','.'],
  107.                 ['.', '#', '.', '#','.'],
  108.                 ['.', '.', '.', '#','.'],
  109.             ],
  110.             13,
  111.             "4x5 with two portals and obstacles"
  112.         ),
  113.         (
  114.             [
  115.                 ['.', '.', '.'],
  116.                 ['.', 'A', '.'],
  117.                 ['.', '.', '.']
  118.             ],
  119.             4,
  120.             "Simple 3x3 with portal in center - direct path better"
  121.         ),
  122.         (
  123.             [
  124.                 ['.', '#', '.'],
  125.                 ['.', 'A', '#'],
  126.                 ['.', '.', '.']
  127.             ],
  128.             4,
  129.             "3x3 with obstacles - portal might help"
  130.         ),
  131.         (
  132.             [
  133.                 ['.', '.', '.', '.'],
  134.                 ['.', 'A', '#', '.'],
  135.                 ['.', '#', 'A', '.'],
  136.                 ['.', '.', '.', '.']
  137.             ],
  138.             4,
  139.             "4x4 with two portals and obstacles"
  140.         ),
  141.        
  142.     ]
  143.    
  144.     print("Running test cases...\n")
  145.     passed = 0
  146.     failed = 0
  147.    
  148.     for i, (matrix, expected, description) in enumerate(test_cases, 1):
  149.         try:
  150.             result = solution.calculateMindisToReachInMatrix(matrix)
  151.             status = "✓ PASS" if result == expected else "✗ FAIL"
  152.            
  153.             if result == expected:
  154.                 passed += 1
  155.             else:
  156.                 failed += 1
  157.            
  158.             print(f"Test {i}: {status}")
  159.             print(f"  Matrix: {len(matrix)}x{len(matrix[0])}")
  160.             print(f"  Description: {description}")
  161.             print(f"  Expected: {expected}, Got: {result}")
  162.            
  163.             # Show matrix structure
  164.             print(f"  Grid:")
  165.             for row in matrix:
  166.                 print(f"    {' '.join(row)}")
  167.         except Exception as e:
  168.             failed += 1
  169.             print(f"Test {i}: ✗ ERROR")
  170.             print(f"  Matrix: {len(matrix)}x{len(matrix[0])}")
  171.             print(f"  Description: {description}")
  172.             print(f"  Error: {e}")
  173.         print()
  174.    
  175.     print(f"Results: {passed} passed, {failed} failed out of {len(test_cases)} tests")
  176.  
  177.  
  178. if __name__ == "__main__":
  179.     main()
  180.  
Advertisement
Add Comment
Please, Sign In to add comment