Island ledgers: Boss receipt
Stuck or curious how this works? Visualize Depth-First Search (DFS) ↗
Inputs
links is a square table of 0s and 1s. Points are numbered from 0. A 1 at links[a][b] joins points a and b in both directions. A 0 means no link.
Your tasks
- Create a list
componentSizes. This graph has two-waylinksbetween points. A group, also called a connected component, contains all points that can reach one another. Start at point 0, then check the other points in number order. Whenever a point has not been visited, explore its whole group depth first: follow a path as far as you can before going back. Record how many points are in that group.componentSizesfollows the order in which you first find the groups. A graph with no points gives an emptycomponentSizes. - Multiply each number in
componentSizesby its position, counting from 1: the first number by 1, the second by 2, and so on. - Add those products. Store the sum in
weightedTotal. - Complete
islandLedgersBossReceiptso it returnsweightedTotal. Return it, do not print it.
Example
If links is [[1, 0, 0, 1, 0, 0], [0, 0, 1, 0, 1, 1], [0, 1, 0, 1, 1, 0], [1, 0, 1, 0, 0, 0], [0, 1, 1, 0, 1, 0], [0, 1, 0, 0, 0, 1]], then componentSizes is [6] and islandLedgersBossReceipt returns 6.
Rules
- If
componentSizesis empty, return 0.
Test data
TEST DATA 1: links is [[1, 0, 1, 1, 0, 0], [0, 1, 1, 0, 1, 1], [1, 1, 0, 0, 0, 1], [1, 0, 0, 0, 1, 0], [0, 1, 0, 1, 1, 0], [0, 1, 1, 0, 0, 0]].
TEST DATA 2: links is [[1, 0, 0, 0, 1], [0, 0, 1, 0, 1], [0, 1, 0, 1, 0], [0, 0, 1, 0, 1], [1, 1, 0, 1, 0]].
Examples
Input: links = [[1,0,1,1,0,0],[0,1,1,0,1,1],[1,1,0,0,0,1],[1,0,0,0,1,0],[0,1,0,1,1,0],[0,1,1,0,0,0]] Output: 6
componentSizes is [6]. Multiply by positions that start at 1: 1 * (6) = 6. Return 6.
Input: links = [[1,0,0,0,1],[0,0,1,0,1],[0,1,0,1,0],[0,0,1,0,1],[1,1,0,1,0]] Output: 5
componentSizes is [5]. Multiply by positions that start at 1: 1 * (5) = 5. Return 5.
Input: links = [] Output: 0
componentSizes is []. There are no numbers to multiply or add, so return 0.
Input limits
- 0 <= input size <= 16.
- Answers fit in a signed 32-bit integer: -2,147,483,648 through 2,147,483,647.
- Input numbers have no decimal part. They range from -1,000,000 to 1,000,000. Follow any extra input rules in task 1.
- The graph has at most 16 points. Its table has the same number of rows and columns. Link entries are 0 or 1; cost entries are 0 through 13.
Efficiency goal
Big-O describes how the work or memory needed grows as the input gets larger.
Efficiency goal: time O(V^2); extra memory, including the helper list, O(n). n is the input length; V is the number of graph points. These labels describe how work and memory grow with the input.
Practice focus
Build componentSizes first, then return exactly what the tasks ask for. Follow the order, keep repeated values when the rule says so, and check the empty case.