--- /dev/null
+from queue import Queue
+
+N, M = tuple(map(int, input().split()))
+
+maze = []
+
+for i in range(N):
+ maze.append(list(input()))
+targets = dict()
+for y, row in enumerate(maze):
+ for x, val in enumerate(row):
+ if val == "S":
+ starting_pos = (x, y)
+ maze[y][x] = '.'
+ elif val == ".":
+ targets[(x, y)] = -1
+# Check Cameras
+temp = [row[:] for row in maze]
+for y, row in enumerate(temp):
+ for x, val in enumerate(row):
+ if val == "C":
+ # check up
+ for i in range(y+1, N):
+ if temp[i][x] == ".":
+ maze[i][x] = "W"
+ elif temp[i][x] == "W" or temp[i][x] == "C":
+ break
+ for i in range(y-1, -1, -1):
+ if temp[i][x] == ".":
+ maze[i][x] = "W"
+ elif temp[i][x] == "W" or temp[i][x] == "C":
+ break
+ for i in range(x+1, M):
+ if temp[y][i] == ".":
+ maze[y][i] = "W"
+ elif temp[y][i] == "W" or temp[y][i] == "C":
+ break
+ for i in range(x-1, -1, -1):
+ if temp[y][i] == ".":
+ maze[y][i] = "W"
+ elif temp[y][i] == "W" or temp[y][i] == "C":
+ break
+ maze[y][x] = 'W'
+
+# Check Conveyors
+for y, row in enumerate(maze):
+ for x, val in enumerate(row):
+ if val == "L":
+ if maze[y][x - 1] in ("R", "W"):
+ maze[y][x] = "W"
+ elif val == "R":
+ if maze[y][x + 1] in ("L", "W"):
+ maze[y][x] = "W"
+ elif val == "U":
+ if maze[y - 1][x] in ("D", "W"):
+ maze[y][x] = "W"
+ elif val == "D":
+ if maze[y + 1][x] in ("U", "W"):
+ maze[y][x] = "W"
+
+# for i in maze:
+# print(*i)
+
+if maze[starting_pos[1]][starting_pos[0]] == 'W':
+ for i in targets.values():
+ print(i)
+ quit()
+
+seen = set()
+q = Queue()
+q.put(starting_pos)
+q.put("|")
+
+movement = {
+ "U": (0, -1),
+ "D": (0, 1),
+ "L": (-1, 0),
+ "R": (1, 0)
+}
+
+steps = 0
+
+while not q.empty():
+ current = q.get()
+
+ if current == "|":
+ steps += 1
+ if not q.empty():
+ q.put("|")
+ continue
+
+ if current in seen:
+ continue
+ else:
+ seen.add(current)
+
+ x, y = current
+
+ while maze[y][x] in movement.keys():
+ t_x = x
+ t_x += movement[maze[y][x]][0]
+ y += movement[maze[y][x]][1]
+ x = t_x
+
+ if (x,y) in targets:
+ if targets[(x,y)] == -1:
+ targets[(x,y)] = steps
+
+
+
+
+ if maze[y - 1][x] == '.':
+ q.put((x, y - 1))
+ elif maze[y - 1][x] in (movement.keys()):
+ q.put((x + movement[maze[y - 1][x]][0], y - 1 + movement[maze[y - 1][x]][1]))
+ if maze[y + 1][x] == '.':
+ q.put((x, y + 1))
+ elif maze[y + 1][x] in (movement.keys()):
+ q.put((x + movement[maze[y + 1][x]][0], y + 1 + movement[maze[y + 1][x]][1]))
+ if maze[y][x - 1] == '.':
+ q.put((x - 1, y))
+ elif maze[y][x - 1] in (movement.keys()):
+ q.put((x - 1 + movement[maze[y][x - 1]][0], y + movement[maze[y][x - 1]][1]))
+ if maze[y][x + 1] == '.':
+ q.put((x + 1, y))
+ elif maze[y][x + 1] in (movement.keys()):
+ q.put((x + 1 + movement[maze[y][x + 1]][0], y + movement[maze[y][x + 1]][1]))
+
+for i in targets.values():
+ print(i)