Each board holds a list of pin IDs, and a pin can appear on several boards. Two pins are connected if they appear on the same board, or if there is a chain of pins from one to the other in which each consecutive pair shares a board. Put another way, treat pins as the nodes of a graph with an edge between any two pins on the same board; two pins are connected when one is reachable from the other.
You are given boards, where boards[i] is the list of pins on board i, and queries, where each query is a pair [pin1, pin2]. Return a list of booleans with one entry per query: True if the two pins are connected and False otherwise.
Function Signature
def pins_connected(boards: list[list[int]], queries: list[list[int]]) -> list[bool]:
Rules
-
A pin ID can appear on any number of boards.
-
A pin is connected to itself, so a query
[p, p]
returns
True
.
-
A board with a single pin connects that pin to no other pin.
-
Entry
i
of the result answers
queries[i]
, in the same order as the queries.
Constraints
-
1 <= len(boards) <= 1000
-
1 <= len(boards[i]) <= 100
-
0 <= boards[i][j] <= 100000
-
1 <= len(queries) <= 1000
-
Every pin ID in a query appears on at least one board.
Examples
Input: boards = [[1, 2, 3], [3, 4, 5], [6, 7]], queries = [[1, 5], [1, 6], [6, 7]]
Output: [True, False, True]
Pin 1 shares board 0 with pin 3, and pin 3 shares board 1 with pin 5, so 1 and 5 are connected. Pins 6 and 7 share board 2, but no board links them to pins 1 to 5, so [1, 6] is False.
Input: boards = [[10, 20], [20, 30], [30, 40], [50, 60]], queries = [[10, 40], [10, 50], [50, 60]]
Output: [True, False, True]
The chain 10, 20, 30, 40 uses boards 0, 1 and 2 in turn. Pins 50 and 60 form a separate group, so 10 cannot reach 50, while 50 and 60 share board 3.
Input: boards = [[5], [1, 2], [2, 5], [7]], queries = [[1, 5], [7, 7], [7, 1]]
Output: [True, True, False]
Board 2 links pin 5 to pin 2, which shares board 1 with pin 1, so 1 and 5 are connected. Pin 7 sits only on a one-pin board, so it is connected to itself and to no other pin.