https://www.acmicpc.net/problem/16928
from collections import deque
import sys
input = sys.stdin.readline
n, m = map(int, input().split())
dice = [1, 2, 3, 4, 5, 6]
ladder = {}
snake = {}
for _ in range(n):
x, y = map(int, input().split())
ladder[x] = y
for _ in range(m):
x, y = map(int, input().split())
snake[x] = y
que = deque()
visited = [int(1e9)] * 101
que.append(1)
visited[1] = 0
while que:
cur = que.popleft()
for i in dice:
next = cur + i
if next in ladder:
next = ladder[next]
if next in snake:
next = snake[next]
if next <= 100 and visited[next] > visited[cur] + 1:
visited[next] = visited[cur] + 1
que.append(next)
print(visited[100])