import sys

file = open(sys.argv[1])
buffer = file.read()
buffer = buffer.split('\n')

wire1 = buffer[0].split(',')
wire2 = buffer[1].split(',')

intersections = [] #List of intersections
wirepoints = {} #Every point on the grid the first wire covers
coord = (0, 0) #Current X and Y coordinate

for lines in wire1:
    if lines[0] == 'U':
        for _ in range(int(lines[1:])):
            coord = (coord[0], coord[1] + 1)
            wirepoints[coord] = 1
    elif lines[0] == 'D':
        for _ in range(int(lines[1:])):
            coord = (coord[0], coord[1] - 1)
            wirepoints[coord] = 1
    elif lines[0] == 'L':
        for _ in range(int(lines[1:])):
            coord = (coord[0] - 1, coord[1])
            wirepoints[coord] = 1
    elif lines[0] == 'R':
        for _ in range(int(lines[1:])):
            coord = (coord[0] + 1, coord[1])
            wirepoints[coord] = 1

coord = [0, 0] #Reset at central port
for lines in wire2:
    if lines[0] == 'U':
        for _ in range(int(lines[1:])):
            coord = (coord[0], coord[1] + 1)
            if coord in wirepoints:
                intersections += [coord]
    elif lines[0] == 'D':
        for _ in range(int(lines[1:])):
            coord = (coord[0], coord[1] - 1)
            if coord in wirepoints:
                intersections += [coord]
    elif lines[0] == 'L':
        for _ in range(int(lines[1:])):
            coord = (coord[0] - 1, coord[1])
            if coord in wirepoints:
                intersections += [coord]
    elif lines[0] == 'R':
        for _ in range(int(lines[1:])):
            coord = (coord[0] + 1, coord[1])
            if coord in wirepoints:
                intersections += [coord]

shortest = abs(intersections[0][0]) + abs(intersections[0][1])
for cross in intersections:
    distance = abs(cross[0]) + abs(cross[1])
    if distance < shortest:
        shortest = distance
        
print("SHORTEST MANHATTEN DISTANCE: ")
print(shortest) #870