""" day_14_02.py """

# usage: python3 day_14_02.py 101 103 < input

import re
import sys


def move(across, down, bots):
    """ move all bots """
    state = {}
    for i, j in bots.items():
        state[i] = [(j[0] + j[2]) % across, (j[1] + j[3]) % down, j[2], j[3]]
    return state


def text(across, down, bots):
    """ visualise robots """
    points = [(x, y) for x, y, _, _ in bots.values()]
    out = ''
    for y in range(down):
        for x in range(across):
            out += 'X' if (x, y) in points else '.'
        out += '\n'
    return out + '\n'


width, height = int(sys.argv[1]), int(sys.argv[2])

robots = {}
with sys.stdin as infile:
    for num, line in enumerate(infile):
        robots[num] = [int(i) for i in re.findall(r'-?\d+', line)]

seconds = 0
while True:
    if len(set((x, y) for x, y, _, _ in robots.values())) == 500:
        # print(text(width, height, robots))
        break
    robots = move(width, height, robots)
    seconds += 1

print(seconds)
