The black king is standing on a chess field consisting of 109 rows and 109 columns. We will consider the rows of the field numbered with integers from 1 to 109 from top to bottom. The columns are similarly numbered with integers from 1 to 109 from left to right. We will denote a cell of the field that is located in the i-th row and j-th column as (i, j).
You know that some squares of the given chess field are allowed. All allowed cells of the chess field are given as n segments. Each segment is described by three integers ri, ai, bi (ai ≤ bi), denoting that cells in columns from number ai to number bi inclusive in the ri-th row are allowed.
Your task is to find the minimum number of moves the king needs to get from square (x0, y0) to square (x1, y1), provided that he only moves along the allowed cells. In other words, the king can be located only on allowed cells on his way.
Let us remind you that a chess king can move to any of the neighboring cells in one move. Two cells of a chess field are considered neighboring if they share at least one point.
Input
The first line contains four space-separated integers x0, y0, x1, y1 (1 ≤ x0, y0, x1, y1 ≤ 109), denoting the initial and the final positions of the king.
The second line contains a single integer n (1 ≤ n ≤ 105), denoting the number of segments of allowed cells. Next n lines contain the descriptions of these segments. The i-th line contains three space-separated integers ri, ai, bi (1 ≤ ri, ai, bi ≤ 109, ai ≤ bi), denoting that cells in columns from number ai to number bi inclusive in the ri-th row are allowed. Note that the segments of the allowed cells can intersect and embed arbitrarily.
It is guaranteed that the king's initial and final position are allowed cells. It is guaranteed that the king's initial and the final positions do not coincide. It is guaranteed that the total length of all given segments doesn't exceed 105.
Output
If there is no path between the initial and final position along allowed cells, print -1.
Otherwise print a single integer — the minimum number of moves the king needs to get from the initial position to the final one.
Examples
Input
5 7 6 11
3
5 3 8
6 7 11
5 2 5
Output
4
Input
3 4 3 10
3
3 1 4
4 5 9
3 10 10
Output
6
Input
1 1 2 10
2
1 1 3
2 6 10
Output
-1
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
We need to solve: King on a huge grid (10^9 x 10^9). Only allowed cells are given as n segments: each segment: row r_i, columns from a_i to b_i inclusive. Total length of segments (sum of (b_i - a_i + 1) but they said total length of all given segments doesn't exceed 10^5). Actually "total length of all given segments" means sum over segments of (b_i - a_i + 1) ≤ 10^5. So total allowed cells is at most 100k. That's crucial.
We need min moves (king moves) from start to target. King moves 8-directionally: can move to any adjacent cell (horizontally, vertically, diagonally). Movement cost per move is 1. So it's a BFS on allowed cells graph. But the grid is huge, but only allowed cells are sparse. We can treat each allowed cell as a node. However there can be up to 100k cells, edges from a node to neighbors (up to 8) but need to consider only allowed neighbors. Naively for each cell, checking its 8 neighbors would be O(number of cells * log?) but we need to know if a neighbor is allowed. Since allowed cells are given as segments per row, we can organize the data: for each row that has any allowed cells, we have a set of intervals (or maybe explicit cells? But segments can be large, but total length ≤ 10^5, so total number of allowed cells across all rows is at most 100k, but intervals may cover many cells; however total length is limited, so the sum of lengths is small. That means if an interval is huge (like from 1 to 10^9), that would be length ~10^9, which violates total length constraint unless n is tiny? Actually they said total length of all given segments doesn't exceed 10^5. So indeed, each segment length (b_i - a_i + 1) sum ≤ 100k. So even if intervals are huge, that would exceed unless they are careful. But the statement: "It is guaranteed that the total length of all given segments doesn't exceed 105." Means total number of cells that are allowed (i.e., sum over segments of number of cells) is ≤ 100k. So each segment could be large only if there are very few segments. For example, if n=1, the segment could be up to length 100k. So allowed cells count ≤ 100k. So we can treat each allowed cell individually? But an interval of length 1e5 would mean 100k cells, that's okay. But if intervals are huge (like 1 to 10^9), that would be length 10^9, which would exceed 100k. So indeed intervals are not that huge. So total number of allowed cells is ≤ 100k.
Thus we can treat each allowed cell as a node. But we have to be careful: if a row has a large contiguous allowed segment, we might need to consider all cells individually? But total cells ≤ 100k, so it's okay to create a node for each cell. However the input representation is given as intervals, and if an interval is long (like 100k), listing all cells would be heavy but we can treat them as range but we need to BFS over cells. Since total cells ≤ 100k, we can actually enumerate all allowed cells? But the input only gives intervals, not explicit cells. We need to convert intervals to explicit cell positions? But intervals can be up to 10^9 but sum of lengths ≤ 100k, so total number of cells is ≤ 100k. So we can, for each interval, iterate over all columns from a_i to b_i, and add each cell (r_i, col) as a node. That would be O(total cells) = up to 100k, which is fine. However there is a catch: intervals might overlap, so cells may be counted multiple times. But we can deduplicate by storing a set of allowed cells. Overlap could cause duplicates, but total distinct cells could still be ≤ 100k? Actually total length sum is ≤ 100k, but if intervals overlap, the union may be less than the sum, but still the sum of lengths counting overlaps is ≤ 100k, so distinct cells ≤ 100k as well. So we can just read all intervals, and for each, iterate over each column in the interval and insert into a set. That would be at most 100k insertions, each O(log N) if using hash set or sorted. So fine.
But wait: The intervals could be like from 1 to 100000, which is 100k cells, that's okay. But if there are many intervals with sum length 100k, it's also okay. So we can just unpack all allowed cells into a set of coordinates (pair of ints). However we must be careful: 10^5 cells, each coordinate stored as pair of ints, fine.
Now BFS on the graph of allowed cells with edges between any two cells that are king-adjacent. The graph size is up to 100k nodes, edges up to 8 per node, so BFS is O(N) essentially. However we need to find neighbors of a given cell quickly. Since we have all allowed cells in a hash set, we can for each of the 8 possible neighbor coordinates, check if that coordinate exists in the set. That would be O(1) average per neighbor. So BFS would be O(N) time and memory.
But there is a nuance: The grid is huge, but we only consider cells that are allowed. However, during BFS, we may need to consider neighbor cells that are allowed but not in our set? Actually we only need to consider allowed cells. So we just check the set. That's fine.
Thus the problem seems straightforward: unpack all intervals into a set of allowed positions, do BFS from start to target.
But wait: The constraints: coordinates up to 1e9, but allowed cells up to 100k. The BFS is fine.
But is there any pitfall? The statement says: "All allowed cells of the chess field are given as n segments. Each segment is described by three integers ri, ai, bi (ai ≤ bi), denoting that cells in columns from number ai to number bi inclusive in the ri-th row are allowed." And "It is guaranteed that the total length of all given segments doesn't exceed 105." So indeed sum of lengths of segments (i.e., sum (b_i - a_i + 1)) ≤ 100k. So we can unpack.
But is there any twist? The king can move diagonally, which means it can change row and column simultaneously. So BFS on a graph with nodes as allowed cells works.
Potential issues: Unpacking all cells from intervals might be trivial, but we must ensure to deduplicate. However, BFS will treat duplicates as same node. So we can read all intervals, store them, then before BFS, we could build a dictionary mapping from (r, c) to something (like index). But we can also just use a hash set for existence and maybe a map to store distance.
But BFS queue: we need to mark visited. We could use a hash map from coordinate to distance. Since we start with start, and only explore allowed cells, the number of visited nodes will be at most total allowed cells.
Edge generation: For a given cell (x, y), its neighbors are (x+dx, y+dy) for dx in {-1,0,1}, dy in {-1,0,1}, not both zero. We check if that coordinate is in allowed set. If yes and not visited, we push with distance+1.
That seems correct.
But is there any possibility that the BFS could exceed memory due to large coordinates? The hash set can store them as 64-bit combined.
Complexities: O(100k) time for building set, BFS O(100k) operations.
Thus the answer is BFS distance or -1 if not reachable.
But wait: Let's double-check sample inputs to confirm.
Sample 1:
Start (5,7) end (6,11)
Segments:
5 3 8 -> row5 cols3-8
6 7 11 -> row6 cols7-11
5 2 5 -> row5 cols2-5 (overlap with first? row5: 2-5 and 3-8 merge to 2-8)
Allowed cells: row5:2-8; row6:7-11.
Now BFS: from (5,7) to (6,11) minimal moves? Possibly:
(5,7) -> (5,8) -> (6,9) -> (6,10) -> (6,11) would be 4? Actually from (5,7) to (6,11) king moves: difference (1,4) so need at least 4 moves because king moves one step in any direction; min moves is max(|dx|,|dy|) = max(1,4)=4 if all moves allowed. So 4 is plausible. BFS would find 4.
Sample 2:
Start (3,4) end (3,10)
Segments:
3 1 4 -> row3 cols1-4
4 5 9 -> row4 cols5-9
3 10 10 -> row3 col10
Allowed cells: row3:1-4 and 10; row4:5-9.
Start at (3,4) end at (3,10). Path? Possibly: (3,4) -> (4,5) (down-right) -> (4,6) -> (4,7) -> (4,8) -> (4,9) -> (3,10) (up-right). That's 6 moves? Actually steps: (3,4) to (4,5) (1 move), to (4,6) (2), to (4,7) (3), to (4,8) (4), to (4,9) (5), to (3,10) (6). So output 6 matches.
Sample 3: Start (1,1) end (2,10). Allowed: row1:1-3; row2:6-10. No path because columns gap: from row1 col3 can't go to row2 col6 directly? King move from (1,3) to (2,4) would be diagonal, but (2,4) not allowed. To get to col10, need to cross columns 4-5 which are not allowed. So -1.
So BFS works.
But is there any hidden complication? Let's think: The total length of segments is ≤ 100k, but there could be many rows, each with many intervals. However, we unpack each interval's cells. That's fine.
But wait: Could there be intervals of length, say, 1e5, and we iterate over each column, that's 100k operations. Sum of lengths is ≤ 100k, so total cells created is ≤ 100k. That's fine.
Thus solution: read start (x0,y0) and end (x1,y1); read n; for i=1..n: read ri, ai, bi; for col from ai to bi: add (ri, col) to set allowed. Also maybe add start and end if they are not included? But they are guaranteed to be allowed, so they will be added when we process intervals. But careful: start and end might be inside intervals that we process. They will be added. But what if an interval is large and we iterate over all columns, then start and end will be included automatically. However if we only add allowed cells from intervals, start and end will be included because they are allowed; they are inside some segment(s). So okay.
But we need to be careful: Since we unpack all cells, we might have duplicates (if intervals overlap). So we can use set to deduplicate.
After building the set, BFS: Use queue of coordinates. We'll need a visited set or map storing distance. Could use unordered_map with pair keys. In C++, we can use unordered_set for allowed and unordered_map for distance, or we can use a map. Since number of nodes is ≤ 100k, even a map with O(log N) is fine.
But we must also ensure that we don't exceed memory due to storing coordinates as pairs. That's fine.
Implementation details:
Represent coordinate as a 64-bit integer: combine row and column into a single key. For example, key = ((long long)r << 32) | c, assuming both ≤ 1e9 which fits in 32 bits. Or simply use pair<int,int> with custom hash.
For BFS, we can maintain a queue of coordinates, and a map (or dictionary) from coordinate to distance.
Starting distance = 0 at start. Push start. While queue not empty, pop front, if it is target return distance. For each neighbor (8 directions), check if neighbor is in allowed set and not visited (i.e., not in distance map). If not visited, set distance = cur+1, push.
If BFS ends without finding target, output -1.
But is there any possibility that the BFS could visit many nodes beyond allowed set? No, only allowed nodes.
So that solves it.
Wait: But total length sum is ≤ 10^5, but what about overlaps? If intervals overlap, the total distinct cells could be less than sum. But we still only generate at most sum cells (including duplicates). However if we generate duplicates by iterating over intervals, we might insert the same cell multiple times into set, but set ensures uniqueness; insertion cost per duplicate may be overhead but not huge. So total operations up to sum length.
Thus algorithm O( total length + visited nodes * 8 ) which is ≤ ~ 2e5, very fast.
I think this is the intended solution for Codeforces problem? I recall a problem "King's Path" (CF #2??) maybe. Actually there is a Codeforces problem 242C "King's Path". I recall that problem: grid 10^9, given allowed cells as segments with total length ≤ 10^5, find king moves. Yes, that's exactly Codeforces 242C. And the solution is BFS on allowed cells using hash set. So I'm confident.
But there is a nuance: In the original problem, total length is sum of lengths, and we need to store allowed cells. Many solutions store allowed cells in a map (like map<int, set>) to represent rows and columns intervals without unpacking each cell. However, because total length ≤ 1e5, unpacking is easier. However, if intervals are huge, but total length small? Actually they said total length of all given segments does not exceed 10^5. So intervals aren't huge individually beyond 1e5? Actually each segment length can be up to 10^5 if there is only one segment. So that's okay. So unpacking is fine.
But we must be careful with memory: storing each cell individually might be okay; each pair of ints 8 bytes, plus overhead of unordered_set, but 100k is fine.
However, an alternative approach that avoids explicit enumeration of all cells: Use map from row to sorted list of intervals, then for BFS neighbor checks, we need to see if a neighbor exists in some interval. That could be more complex. Since we have limited number of cells, enumeration is simpler.
But wait: In the problem statement, they guarantee total length ≤ 10^5, meaning sum of (b_i - a_i + 1) ≤ 10^5. So the number of allowed cells is at most 100k. So indeed enumeration is fine.
Thus solution is straightforward.
Edge Cases: start and end same? Not allowed.
Check: If there are many intervals but total length small, we can process.
Implementation in Python: Use set of allowed cells: allowed = set(). For each segment, for col in range(a, b+1): allowed.add((r, col)). However, if an interval is long (e.g., 100k), the loop is fine. But if there are many intervals with sum length 100k, loops also fine.
BFS: Use deque. visited = dict() or use set for visited and store distance separately. Could use dict: dist = { (x0,y0):0 }. Then BFS.
For each neighbor: nr = x+dx, nc = y+dy. If (nr,nc) in allowed and (nr,nc) not in dist: dist[(nr,nc)] = dist[(x,y)]+1; queue.append((nr,nc)). If neighbor equals target, return dist+1.
If queue exhausted, return -1.
But Python might be slower for loops over 100k and BFS with hash set of tuples, but it's fine.
But careful: The neighbor directions: 8 directions: dx = [-1,0,1] and dy = [-1,0,1] excluding (0,0). So we can loop.
Potential optimization: Use bitpacking for coordinates: e.g., combine into a single integer: key = (r << 32) | c, but not needed.
Now test sample:
Sample 1: start (5,7) target (6,11). allowed from intervals: (5,3..8) and (6,7..11) and (5,2..5). So allowed set includes (5,2-8) and (6,7-11). BFS from (5,7) should find distance 4.
Sample 2: etc.
Potential pitfalls: The row and column coordinates up to 1e9, but Python int handles.
One more thing: Input might have duplicate intervals; if we unpack we deduplicate automatically.
Thus solution is ready.
But I recall that some solutions use map<int, set> to store intervals and use lower_bound to check presence; but enumeration is simpler.
Thus final answer: implement BFS.
Now we need to produce output accordingly.
I will write code accordingly.
Let's think about complexity: Building allowed set: sum lengths ≤ 100k, so at most 100k insertions. BFS: number of visited nodes ≤ total allowed cells (maybe less). Each node processes up to 8 neighbor checks. So total operations ~ 800k, fine.
Edge Cases: Might there be allowed cells that are isolated but BFS only visits reachable ones, so visited may be less.
Thus final solution.
But wait: The problem statement says "total length of all given segments doesn't exceed 105." Is that sum of lengths of intervals (b_i - a_i + 1) or something else? In Codeforces problem 242C, it's exactly that. So yes.
Thus I'll code.
Implementation Steps:
Read x0, y0, x1, y1.
Read n.
allowed = set()
For i in range(n):
read r, a, b.
for col in range(a, b+1):
allowed.add( (r, col) )
Check if start and end are in allowed? Guaranteed, but we can ignore.
BFS:
from collections import deque
queue = deque()
dist = {}
dist[(x0,y0)] = 0
queue.append((x0,y0))
while queue:
x,y = queue.popleft()
d = dist[(x,y)]
if x==x1 and y==y1:
print(d)
return
for dx in (-1,0,1):
for dy in (-1,0,1):
if dx==0 and dy==0: continue
nx, ny = x+dx, y+dy
if (nx,ny) in allowed and (nx,ny) not in dist:
dist[(nx,ny)] = d+1
queue.append((nx,ny))
print(-1)
That's it.
But we must be careful about performance of "in allowed" with tuple hashing; it's okay for 100k.
One more improvement: Since allowed set may contain many cells, we could also remove visited cells from allowed to avoid using separate dist dict? That is, we could use allowed set also as visited: when we visit a cell, we remove it from allowed. Then we don't need a separate visited set. That might be faster and simpler: allowed = set of all allowed cells. BFS: queue start, remove start from allowed. Then for each neighbor, if neighbor in allowed, remove and push. This way we don't need dist dict? We still need distance to target. So we can store distance in queue as a tuple (x,y,dist) or keep separate distance array. Or use two queues with BFS level. Simpler: keep dist in a dict or use queue with (x,y,dist). Since we remove from allowed, we don't need visited check; we just check if neighbor in allowed.
But we also need distance to output. We can store distance as separate dict or compute levels by BFS layers: while queue, for each level increment. That's also possible. But simplest: use dict.
Given small size, both fine.
Thus final code.
But wait: Is it guaranteed that total length (sum of lengths) ≤ 100k? If yes, unpacking is safe. However, some may argue that if there is a segment from 1 to 1e9, length 1e9, that would exceed total length. So no such segment.
Thus done.
Now I should produce final answer: code in Python.
But sometimes Python can be slow for loops with up to 100k + BFS up to 100k, but it's fine.
Double-check input: The first line contains four integers x0, y0, x1, y1. However note: they list rows first? Actually problem statement: "The first line contains four space-separated integers x0, y0, x1, y1" but earlier they defined rows as i and columns as j; they used (i,j). But here they wrote x0, y0 etc. Possibly x is row and y is column. In the sample: start (5,7) and end (6,11) which matches rows 5,6. So x is row, y is column. So our code uses (x,y) accordingly.
Now, there is nuance: In BFS we treat coordinates as (row, col). The king moves to neighboring cells, i.e., row change within ±1, col change within ±1.
Thus BFS as described.
Now, consider memory: If we store all allowed cells as set of tuples, each tuple overhead is large but still within memory for 100k.
Now, we should consider that reading input and unpacking may be time-consuming if we use Python loops for each column over ranges up to 100k total. That's okay.
But there is potential issue: If intervals are many and each of moderate length, we will call allowed.add many times. That's okay.
But we need to ensure we use sys.stdin.read for faster input.
I'll implement using sys.stdin.readline.
Edge Cases: If start == target? Not allowed.
Now, implement solve().
Pseudo:
import sys
from collections import deque
def solve():
data = sys.stdin.read().strip().split()
if not data: return
it = iter(data)
x0 = int(next(it)); y0 = int(next(it)); x1 = int(next(it)); y1 = int(next(it))
n = int(next(it))
allowed = set()
for _ in range(n):
r = int(next(it)); a = int(next(it)); b = int(next(it))
for col in range(a, b+1):
allowed.add((r, col))
# BFS
start = (x0, y0)
target = (x1, y1)
# ensure start and target are in allowed? They should be.
if start == target:
print(0)
return
q = deque()
q.append(start)
dist = {start: 0}
# optionally remove start from allowed? But we use dist for visited.
while q:
x, y = q.popleft()
d = dist[(x, y)]
if (x, y) == target:
print(d)
return
for dx in (-1, 0, 1):
for dy in (-1, 0, 1):
if dx == 0 and dy == 0:
continue
nx, ny = x+dx, y+dy
if (nx, ny) in allowed and (nx, ny) not in dist:
dist[(nx, ny)] = d+1
q.append((nx, ny))
print(-1)
if name == "main":
solve()
This should work.
But I'm concerned about the memory/time of building allowed set by iterating over each column for intervals that may be up to 100k in length. That's fine.
But note: The input could be up to 100k intervals? Actually n up to 10^5. But total length ≤ 10^5, so the sum of lengths is small, but n can be as high as 10^5. That means many intervals could be of length 1. So we will iterate over each interval's range. For each interval, we do a loop from a to b inclusive. That's fine because total number of iterations across all intervals equals total length, which is ≤ 100k. So overall loops are fine.
But what about memory? The allowed set will contain at most 100k entries, plus BFS dist map up to that many.
Thus all good.
Now, finalize answer.
But wait: There is a known alternative solution: using BFS on intervals without enumerating each cell. But our simple approach is accepted for 242C. I've seen many Python solutions using exactly this.
But I recall that Python solutions for CF 242C sometimes use dictionary mapping row to set of columns, but still need to check neighbors quickly. Our set of tuples is okay.
One more nuance: The coordinates are up to 1e9, but when we check neighbor existence, we compute (nx, ny) and look up in allowed set. That's fine.
Start (5,7) d=0.
Neighbors: we check all 8.
(4,6) not allowed? Not in allowed.
(4,7) not allowed? Not in allowed (row4 not allowed).
(4,8) not allowed.
(5,6) allowed? (5,6) is in row5 col6? row5 allowed cols2-8, so yes (5,6) is allowed, so visit d=1.
(5,7) itself skip.
(5,8) allowed (5,8) row5 col8 is allowed, visit d=1.
(6,6) not allowed? row6 allowed cols7-11, col6 not allowed.
(6,7) allowed, visit d=1.
(6,8) allowed, visit d=1.
Then continue BFS. Eventually reach (6,11) with d=4. Good.
Sample 2: similar.
Sample 3: should output -1.
Thus code works.
Now potential pitfalls: Input reading: The first line has 4 ints, second line has n, then n lines. Our reading using split and iter works.
One more: In BFS we use dist dict to track visited. Could also use set visited and store distances separately. But fine.
Time: BFS might push up to 100k nodes, each neighbor check 8 lookups. So 800k set lookups. In Python, with tuple hashing, it's okay.
Now confirm with constraints: n up to 100k, total length 100k. So allowed set size up to 100k. BFS is fine.
Thus final answer.
But wait: There's a subtlety: The problem statement says "total length of all given segments doesn't exceed 10^5". Could that be misinterpreted as the total number of segments? But phrase "total length" clearly means sum of lengths. In Codeforces 242C, it's indeed sum of lengths. So okay.
Therefore, solution is correct.
Now I will output the code with explanation.
But the user asked: "You are an AI assistant. Answer as... Provide final answer with code." So I'll produce final answer: explanation and code.
Thus final. We can treat each allowed cell as a node in a graph, where edges exist between king-adjacent cells. Since the total number of allowed cells is at most 10⁵ (given by the constraint on the sum of segment lengths), we can explicitly list all allowed cells, store them in a hash set, and then run a BFS from the start to the target.
Algorithm
Read the start (x0, y0) and target (x1, y1).
Read the number of segments n.
For each segment (r, a, b), iterate over all columns from a to b and add the pair (r, col) to a set allowed. This set will contain every cell that the king may occupy.
Perform a BFS starting from (x0, y0):
Use a queue (deque) and a dictionary dist to store visited cells and their distances.
For each popped cell, check if it is the target; if yes, return its distance.
Generate its 8 neighbors (row ±1, col ±1). For each neighbor, if it is in allowed and not yet visited, set its distance to current distance + 1 and push it into the queue.
If the queue becomes empty without reaching the target, output -1.
Complexity
Time: O( L + V ), where L ≤ 10⁵ is the total number of allowed cells and V ≤ 10⁵ is the number of visited cells. Each cell processes at most 8 neighbor checks.
Space: O( L ) for the set of allowed cells and the BFS data structures.
Code (Python)
python
import sys
from collections import deque
def solve() -> None:
data = sys.stdin.buffer.read().split()
if not data:
return
it = iter(data)
x0 = int(next(it)); y0 = int(next(it))
x1 = int(next(it)); y1 = int(next(it))
n = int(next(it))
allowed = set()
for _ in range(n):
r = int(next(it)); a = int(next(it)); b = int(next(it))
# add every cell of this segment
for col in range(a, b + 1):
allowed.add((r, col))
start = (x0, y0)
target = (x1, y1)
# BFS
q = deque([start])
dist = {start: 0}
directions = [(-1, -1), (-1, 0), (-1, 1),
(0, -1), (0, 1),
(1, -1), (1, 0), (1, 1)]
while q:
x, y = q.popleft()
d = dist[(x, y)]
if (x, y) == target:
print(d)
return
for dx, dy in directions:
nx, ny = x + dx, y + dy
if (nx, ny) in allowed and (nx, ny) not in dist:
dist[(nx, ny)] = d + 1
q.append((nx, ny))
print(-1)
if __name__ == "__main__":
solve()