Use this to learn the idea, then write your own version.
123 45 6import sys7from collections import deque8input = sys.stdin.readline9 10def output(graph):11 for row in graph:12 print(*row)13 14def good(R, C):15 return 0 <= R < r and 0 <= C < c16 17def isConve(R, C):18 return graph[R][C] in {"L", "R", "U", "D"}19 20def canGo(R, C):21 return isConve(R, C) or graph[R][C] == "."22 23def cv(R, C):24 dirn = {"L": [0, -1], "R": [0, 1], "U": [-1, 0], "D": [1, 0]}25 return dirn[graph[R][C]]26 27def conveyor(start):28 cur = start29 curR = start[0]30 curC = start[1]31 d = cv(curR, curC)32 while True:33 nxtR, nxtC = curR + d[0], curC + d[1]34 if good(nxtR, nxtC) and isConve(nxtR, nxtC) and not vis[nxtR][nxtC]:35 vis[nxtR][nxtC] = True36 dis[nxtR][nxtC] = dis[curR][curC]37 curR, curC = nxtR, nxtC38 d = cv(curR, curC)39 else:40 break41 return [nxtR, nxtC]42 4344r, c = map(int, input().split())45graph = [list(input().strip()) for i in range(r)]46start = []47 484950flg = False51for i in range(r):52 for j in range(c):53 if graph[i][j] == "S":54 start = [i, j]55 graph[i][j] = "."56 flg = True57 break58 if flg:59 break60 6162for i in range(r):63 for j in range(c):64 if graph[i][j] == "C":65 66 for s in range(j-1, -1, -1):67 if graph[i][s] == "W":68 break69 if graph[i][s] == ".":70 graph[i][s] = "F"71 72 for s in range(j+1, c):73 if graph[i][s] == "W":74 break75 if graph[i][s] == ".":76 graph[i][s] = "F"77 78 for s in range(i - 1, -1, -1):79 if graph[s][j] == "W":80 break81 if graph[s][j] == ".":82 graph[s][j] = "F"83 84 for s in range(i + 1, r):85 if graph[s][j] == "W":86 break87 if graph[s][j] == ".":88 graph[s][j] = "F"89 9091if graph[start[0]][start[1]] == "F":92 cnt = -193 for i in range(r):94 for j in range(c):95 if graph[i][j] == "." or graph[i][j] == "F":96 cnt += 197 for i in range(cnt):98 print(-1)99 sys.exit(0)100 101102dis = [[float("inf")] * c for i in range(r)]103vis = [[False] * c for i in range(r)]104q = deque([start])105vis[start[0]][start[1]] = True106dis[start[0]][start[1]] = 0107while q:108 cur = q.popleft()109 curR = cur[0]110 curC = cur[1]111 if graph[curR][curC] == "." or graph[curR][curC] == "S":112 for d in [[0, 1], [0, -1], [1, 0], [-1, 0]]:113 nxtR = curR + d[0]114 nxtC = curC + d[1]115 if good(nxtR, nxtC) and not vis[nxtR][nxtC]:116 if graph[nxtR][nxtC] == ".":117 vis[nxtR][nxtC] = True118 dis[nxtR][nxtC] = dis[curR][curC] + 1119 q.append([nxtR, nxtC])120 elif isConve(nxtR, nxtC):121 vis[nxtR][nxtC] = True122 dis[nxtR][nxtC] = dis[curR][curC] + 1123 offR, offC = conveyor([nxtR, nxtC])124 if good(offR, offC) and not vis[offR][offC] and canGo(offR, offC):125 vis[offR][offC] = True126 dis[offR][offC] = dis[nxtR][nxtC]127 q.append([offR, offC])128 129for i in range(r):130 for j in range(c):131 if (graph[i][j] == "." or graph[i][j] == "F") and start != [i, j]:132 print(dis[i][j] if vis[i][j] else -1)