{"id":"maximum-number-of-accepted-invitations","title":"Maximum Number of Accepted Invitations","difficulty":"medium","patterns":["bipartite-matching"],"primaryConcept":"graph-bipartite-matching","concepts":["graph-bipartite-matching"],"problemForm":"core","companies":["Google","Meta","Amazon"],"category":"trees-graphs","executionStyle":"solution-method","compareMode":"exact","syntheticTestConfig":{"inputShape":"matrix","primaryParam":"grid","sizeMetric":"matrix-cells","constraints":["binary"]},"description":"There are `m` boys and `n` girls. You are given a binary matrix `grid` where `grid[i][j] == 1` means boy `i` can invite girl `j`, and `grid[i][j] == 0` means he cannot.\n\nEach boy can invite at most one girl, and each girl can accept at most one invitation. Return the maximum number of accepted invitations.","examples":[{"input":"grid = [[1,1,1],[1,0,1],[0,0,1]]","output":"3","explanation":"All three boys can be matched to distinct girls."},{"input":"grid = [[1,0,1,0],[1,0,0,0],[0,0,1,0],[1,1,1,0]]","output":"3","explanation":"At most three girls can accept because the fourth girl has no incoming invitation."}],"constraints":[{"id":"1-m-n-200","text":"1 <= m, n <= 200","check":[{"kind":"sizeRange","target":"grid","measure":"matrixRows","min":1,"max":200},{"kind":"valueRange","target":"grid","selector":"arrayItemLengths","min":1,"max":200}]},{"id":"grid-length-m","text":"len(grid) == m"},{"id":"grid-i-length-n","text":"len(grid[i]) == n"},{"id":"grid-i-j-is-0-or-1","text":"grid[i][j] is 0 or 1","check":{"kind":"domain","target":"grid","selector":"nestedArrayItems","allowed":[0,1],"rectangular":true}}],"starterCode":"class Solution:\n    def maximumInvitations(self, grid: list[list[int]]) -> int:\n        # Your code here\n        pass","functionName":"maximumInvitations","testCases":[{"id":"1","input":{"grid":[[1,1,1],[1,0,1],[0,0,1]]},"expected":3,"description":"A matching can accept every boy."},{"id":"2","input":{"grid":[[1,0,1,0],[1,0,0,0],[0,0,1,0],[1,1,1,0]]},"expected":3,"description":"One girl column has no compatible boy."},{"id":"3","input":{"grid":[[0,0],[0,0]]},"expected":0,"description":"No compatible invitations."},{"id":"4","input":{"grid":[[1,0],[1,0],[0,1]]},"expected":2,"description":"The number of girls caps the answer."},{"id":"h1","input":{"grid":[[1]]},"expected":1,"description":"A 1x1 matching can only accept one invitation."},{"id":"h2","input":{"grid":[[1,0],[0,1]]},"expected":2,"description":"A diagonal 2x2 grid matches both boys."},{"id":"h3","input":{"grid":[[1,1],[1,0]]},"expected":2,"description":"A reassignment path is needed to match both boys."},{"id":"h4","input":{"grid":[[1,0,0],[1,1,0],[0,1,1]]},"expected":3,"description":"Three boys can be matched through a simple chain."},{"id":"h5","input":{"grid":[[1,1,0,0],[0,1,1,0],[0,0,1,1]]},"expected":3,"description":"A staggered chain still reaches full matching size."},{"id":"h6","input":{"grid":[[1,0,0,0],[1,1,0,0],[0,1,1,0],[0,0,0,0]]},"expected":3,"description":"An unmatched boy does not change the best matching size."},{"id":"more-girls-than-boys","input":{"grid":[[1,0,1,0],[0,1,0,1]]},"expected":2,"description":"The number of boys caps accepted invitations even with extra compatible girls."},{"id":"right-side-cap-with-reassignment","input":{"grid":[[1,1,0],[1,0,0],[0,1,1],[0,0,1]]},"expected":3,"description":"Four boys compete for three girls, with reassignment needed to fill every girl."},{"id":"one-boy-second-girl","input":{"grid":[[0,1]]},"expected":1,"description":"One boy and two girls, and he can only invite the second girl."}],"hints":[{"level":1,"content":"Treat boys and girls as the two sides of a bipartite graph."},{"level":2,"content":"When a girl is already matched, try to reroute her current boy through another option."},{"level":3,"content":"Each root DFS needs a fresh visited array so one search does not block another."}],"guidedFlow":{"version":2,"approachSelection":{"contract":"approach-selection-v1","question":"Which approach should we implement?","decisionPrompt":"Choose the approach whose state and complexity match the problem constraints.","approaches":[{"id":"greedy-free-only","name":"Take only free girls","summary":"Give each boy the first currently free compatible girl.","decisionReason":"It hands boy 0 the first girl it can reach and never reconsiders, so a later boy whose only girl is taken goes unmatched even when a swap would have paired both.","complexity":{"time":"O(m*n)","space":"O(n)"},"tradeoffs":["Runs in O(m*n) time and uses O(n) space."],"isOptimal":false},{"id":"augmenting-path","name":"Augmenting-path matching","summary":"Run a DFS from each boy that claims a free girl or asks a taken girl's current boy to move aside.","decisionReason":"The DFS makes the relocation chain concrete: each boy either takes a free girl or pushes the current owner down its own options, recovering the invitations greedy drops.","complexity":{"time":"O(m * E)","space":"O(E + n)"},"tradeoffs":["Runs in O(m * E) time and uses O(E + n) space."],"isOptimal":true}]},"codingCheckpoints":[{"id":"build-adj","title":"Build compatibility edges","description":"Convert each matrix row into the girls that boy can invite.","commonMistakes":["Scanning the raw matrix inside every DFS call","Dropping valid edges while building adjacency"],"hint":"Build `adj[boy]` from the columns where `grid[boy][girl] == 1`.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"bipartite-matching","fact":"builds_bipartite_adjacency_state","scope":"build-adj","readMode":"bipartite-matching-value-query-v1"}]},"semanticSpec":{"intent":"Build reusable boy-to-girl adjacency before running matching.","doneWhen":"Every 1 in the compatibility matrix becomes an edge in adjacency state.","shouldFailWhen":"The code never builds an adjacency structure from grid edges.","roles":["boy","girl","adjacency list"],"mustProve":["The solution builds bipartite adjacency state from compatible matrix entries."],"mustNotAccept":["Using an unrelated graph or ignoring zero entries."],"proofSnippets":[{"id":"py-maximum-invitations-build-adj","language":"python","code":"def maximumInvitations(grid):\n    adj = [[] for _ in range(len(grid))]\n    for boy in range(len(grid)):\n        for girl in range(len(grid[0])):\n            if grid[boy][girl] == 1:\n                adj[boy].append(girl)"}]}},{"id":"init-match","title":"Initialize the match state","description":"Create the array that records which boy is currently matched to each girl, using -1 for unmatched girls.","commonMistakes":["Sizing the match array by the number of boys instead of girls","Using a non-sentinel initial value that cannot distinguish unmatched girls"],"hint":"After building compatibility edges, initialize one slot per girl with -1 so DFS can tell whether a girl is unmatched or needs rerouting.","semanticSpec":{"intent":"Prepare the right-side ownership state used by augmenting-path DFS.","doneWhen":"This step is done when the code creates a match array with one entry per girl and initializes each entry to an unmatched sentinel.","shouldFailWhen":"This step should fail if the match state is missing, has the wrong size, or starts with values that look already matched.","roles":["right-side match state","unmatched sentinel","girl count"],"mustProve":["The match state has one slot for each girl.","Every slot starts as unmatched before DFS runs."],"mustNotAccept":["A match array sized by the number of boys.","A match state initialized with real boy ids before search starts."],"equivalentVariants":["Use -1, None, or another clear unmatched sentinel if the later DFS checks the same sentinel.","Name the match state match, owner, assigned, or any equivalent ownership variable."],"proofSnippets":[{"id":"py-maximum-invitations-init-match","language":"python","code":"def maximumInvitations(grid):\n    boys = len(grid)\n    girls = len(grid[0])\n    adj = [[] for _ in range(boys)]\n    for boy in range(boys):\n        for girl in range(girls):\n            if grid[boy][girl] == 1:\n                adj[boy].append(girl)\n    match = [-1] * girls"}]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"bipartite-matching","fact":"initializes_match_state","scope":"init-match","readMode":"bipartite-matching-value-query-v1"}]}},{"id":"dfs-match","title":"Implement augmenting DFS","description":"Claim a free girl or recursively reroute the boy currently matched to her.","commonMistakes":["Treating an occupied girl as permanently unavailable","Forgetting the visited guard inside DFS"],"hint":"A girl can be used if she is free or if her current match can move elsewhere.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"bipartite-matching","fact":"defines_augmenting_reroute_helper","scope":"dfs-match","readMode":"bipartite-matching-value-query-v1"}]},"semanticSpec":{"intent":"Define the augmenting-path helper that can reroute existing matches.","doneWhen":"DFS writes a match when a girl is free or when her current owner can be recursively rerouted.","shouldFailWhen":"The helper never tries to reroute current owners.","roles":["augmenting helper","match state","visited state"],"mustProve":["The solution defines an augmenting reroute helper."],"mustNotAccept":["A greedy helper that only accepts currently free girls."],"proofSnippets":[{"id":"py-maximum-invitations-dfs-match","language":"python","code":"def maximumInvitations(grid):\n    boys = len(grid)\n    girls = len(grid[0])\n    adj = [[] for _ in range(boys)]\n    for boy in range(boys):\n        for girl in range(girls):\n            if grid[boy][girl] == 1:\n                adj[boy].append(girl)\n    match = [-1] * girls\n    def dfs(boy, seen):\n        for girl in adj[boy]:\n            if seen[girl]:\n                continue\n            seen[girl] = True\n            if match[girl] == -1 or dfs(match[girl], seen):\n                match[girl] = boy\n                return True\n        return False"}]}},{"id":"match-and-return","title":"Run searches and return count","description":"Try one fresh visited-state DFS per boy and return the number of successful matches.","commonMistakes":["Reusing visited state across root searches","Returning the match array instead of the count"],"hint":"Create `seen` inside the outer loop, call DFS, and increment the answer only when it succeeds.","validation":{"type":"semantic","validator":"all","params":[{"type":"semantic","validator":"familyFact","params":[{"family":"bipartite-matching","fact":"runs_augmenting_search_with_initialized_match_state","scope":"match-and-return","readMode":"bipartite-matching-value-query-v1"}]},{"type":"semantic","validator":"familyFact","params":[{"family":"bipartite-matching","fact":"allocates_visited_per_root_search","scope":"reset-seen","readMode":"bipartite-matching-value-query-v1"}]},{"type":"semantic","validator":"familyFact","params":[{"family":"bipartite-matching","fact":"executes_augmenting_search_with_fresh_visited_state","scope":"reset-seen","readMode":"bipartite-matching-value-query-v1"}]},{"type":"semantic","validator":"familyFact","params":[{"family":"bipartite-matching","fact":"returns_matching_size_after_augmenting_search","scope":"match-and-return","readMode":"bipartite-matching-value-query-v1"}]}]},"semanticSpec":{"intent":"Run the matching search from each boy with fresh visited state and return the matching size.","doneWhen":"The outer loop allocates fresh visited state, runs DFS, updates the count, and returns that count after all boys are processed.","shouldFailWhen":"The code reuses visited state, omits the match count update, or returns before all searches finish.","roles":["fresh visited state","matching count","outer search loop"],"mustProve":["The solution runs augmenting searches with initialized match state and fresh per-root visited state.","The solution returns the final matching size."],"mustNotAccept":["A single shared visited array for every root search.","Returning unrelated state."],"proofSnippets":[{"id":"py-maximum-invitations-match-and-return","language":"python","code":"def maximumInvitations(grid):\n    boys = len(grid)\n    girls = len(grid[0])\n    adj = [[] for _ in range(boys)]\n    for boy in range(boys):\n        for girl in range(girls):\n            if grid[boy][girl] == 1:\n                adj[boy].append(girl)\n    match = [-1] * girls\n    def dfs(boy, seen):\n        for girl in adj[boy]:\n            if seen[girl]:\n                continue\n            seen[girl] = True\n            if match[girl] == -1 or dfs(match[girl], seen):\n                match[girl] = boy\n                return True\n        return False\n    invited = 0\n    for boy in range(boys):\n        seen = [False] * girls\n        if dfs(boy, seen):\n            invited += 1\n    return invited"}]}}],"slides":[{"id":"read-the-problem","chapter":"The task","kind":"info","eyebrow":"Read the problem","title":"Accept as many invitations as you can","workspacePanel":"problem","body":["You get an m-by-n binary matrix grid. A 1 at grid[boy][girl] means that boy can invite that girl; a 0 means he cannot. Each boy invites at most one girl and each girl accepts at most one invitation. Return how many invitations can be accepted at once.","Each accepted invitation uses up one boy and one girl, so the answer can never exceed the smaller side."]},{"id":"greedy-baseline","chapter":"The obvious way","kind":"code-trace","eyebrow":"The obvious way","title":"Hand each boy the first free girl he can invite","summary":"Walk the boys in order, and for each one take the first girl on his list that nobody has accepted yet.","workspacePanel":"trace","codeTrace":{"contract":"guided-code-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"def maximumInvitations(grid: list[list[int]]) -> int:\n    boys = len(grid)\n    girls = len(grid[0])\n    adj: list[list[int]] = [[] for _ in range(boys)]\n    for boy in range(boys):\n        for girl in range(girls):\n            if grid[boy][girl] == 1:\n                adj[boy].append(girl)\n    taken = [False] * girls\n    invited = 0\n    for boy in range(boys):\n        for girl in adj[boy]:\n            if not taken[girl]:\n                taken[girl] = True\n                invited += 1\n                break\n    return invited","steps":[{"id":"boy0","title":"Boy 0 takes the first free girl","codeLine":13,"summary":"Boy 0's options are girl 0 then girl 1. Girl 0 is free, so boy 0 grabs her and stops looking.","state":{"graph":{"nodes":[{"id":"B0","label":"B0"},{"id":"B1","label":"B1"},{"id":"G0","label":"G0"},{"id":"G1","label":"G1"}],"edges":[["B0","G0"],["B0","G1"],["B1","G0"]],"current":"B0","highlighted":["G0"],"activeEdges":[["B0","G0"]]}}},{"id":"boy1","title":"Boy 1 finds his only option already taken","codeLine":13,"summary":"Boy 1 can invite only girl 0, but boy 0 holds her. The loop finds nothing free and leaves boy 1 unmatched.","state":{"graph":{"nodes":[{"id":"B0","label":"B0"},{"id":"B1","label":"B1"},{"id":"G0","label":"G0"},{"id":"G1","label":"G1"}],"edges":[["B0","G0"],["B0","G1"],["B1","G0"]],"current":"B1","highlighted":["G0"],"activeEdges":[["B0","G0"]]}}},{"id":"result","title":"Greedy returns 1","codeLine":17,"summary":"Only boy 0 is matched, so this returns 1. Girl 1 sat free the whole time while boy 1 went unpaired.","state":{"graph":{"nodes":[{"id":"B0","label":"B0"},{"id":"B1","label":"B1"},{"id":"G0","label":"G0"},{"id":"G1","label":"G1"}],"edges":[["B0","G0"],["B0","G1"],["B1","G0"]],"activeEdges":[["B0","G0"]]}}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"const boys = grid.length;\nconst girls = grid[0].length;\nconst adj = Array.from({ length: boys }, () => []);\nfor (let boy = 0; boy < boys; boy++) {\n    for (let girl = 0; girl < girls; girl++) {\n        if (grid[boy][girl] === 1) {\n            adj[boy].push(girl);\n        }\n    }\n}\nconst taken = Array(girls).fill(false);\nlet invited = 0;\nfor (let boy = 0; boy < boys; boy++) {\n    for (const girl of adj[boy]) {\n        if (!taken[girl]) {\n            taken[girl] = true;\n            invited++;\n            break;\n        }\n    }\n}\nreturn invited;","lineMap":{"2":1,"3":2,"4":3,"5":4,"6":5,"7":6,"8":7,"9":11,"10":12,"11":13,"12":14,"13":15,"14":16,"15":17,"16":18,"17":22},"statementBundles":{"8":{"startLine":7,"endLine":10},"16":{"startLine":18,"endLine":21}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"const boys = grid.length;\nconst girls = grid[0].length;\nconst adj: Array<Array<number>> = Array.from({ length: boys }, () => []);\nfor (let boy = 0; boy < boys; boy++) {\n    for (let girl = 0; girl < girls; girl++) {\n        if (grid[boy][girl] === 1) {\n            adj[boy].push(girl);\n        }\n    }\n}\nconst taken = Array(girls).fill(false);\nlet invited = 0;\nfor (let boy = 0; boy < boys; boy++) {\n    for (const girl of adj[boy]) {\n        if (!taken[girl]) {\n            taken[girl] = true;\n            invited++;\n            break;\n        }\n    }\n}\nreturn invited;","lineMap":{"2":1,"3":2,"4":3,"5":4,"6":5,"7":6,"8":7,"9":11,"10":12,"11":13,"12":14,"13":15,"14":16,"15":17,"16":18,"17":22},"statementBundles":{"8":{"startLine":7,"endLine":10},"16":{"startLine":18,"endLine":21}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"int boys = grid.size();\nint girls = grid.get(0).size();\nList<List<Integer>> adj = new ArrayList<>();\nfor (int i = 0; i < boys; i++) {\n    adj.add(new ArrayList<>());\n}\nfor (int boy = 0; boy < boys; boy++) {\n    for (int girl = 0; girl < girls; girl++) {\n        if (grid.get(boy).get(girl) == 1) {\n            adj.get(boy).add(girl);\n        }\n    }\n}\nList<Boolean> taken = new ArrayList<>();\nfor (int index = 0; index < girls; index++) {\n    taken.add(false);\n}\nint invited = 0;\nfor (int boy = 0; boy < boys; boy++) {\n    for (Integer girl : adj.get(boy)) {\n        if (!taken.get(girl)) {\n            taken.set(girl, true);\n            invited++;\n            break;\n        }\n    }\n}\nreturn invited;","lineMap":{"2":1,"3":2,"4":3,"5":7,"6":8,"7":9,"8":10,"9":14,"10":18,"11":19,"12":20,"13":21,"14":22,"15":23,"16":24,"17":28},"statementBundles":{"4":{"startLine":3,"endLine":6},"8":{"startLine":10,"endLine":13},"9":{"startLine":14,"endLine":17},"16":{"startLine":24,"endLine":27}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"int boys = grid.Count;\nint girls = grid[0].Count;\nList<List<int>> adj = Enumerable.Range(0, boys).Select(_ => new List<int>()).ToList();\nfor (int boy = 0; boy < boys; boy++) {\n    for (int girl = 0; girl < girls; girl++) {\n        if (grid[boy][girl] == 1) {\n            adj[boy].Add(girl);\n        }\n    }\n}\nList<bool> taken = Enumerable.Repeat<bool>(false, girls).ToList();\nint invited = 0;\nfor (int boy = 0; boy < boys; boy++) {\n    foreach (int girl in adj[boy]) {\n        if (!taken[girl]) {\n            taken[girl] = true;\n            invited++;\n            break;\n        }\n    }\n}\nreturn invited;","lineMap":{"2":1,"3":2,"4":3,"5":4,"6":5,"7":6,"8":7,"9":11,"10":12,"11":13,"12":14,"13":15,"14":16,"15":17,"16":18,"17":22},"statementBundles":{"8":{"startLine":7,"endLine":10},"16":{"startLine":18,"endLine":21}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"int boys = grid.size();\nint girls = grid[0].size();\nvector<vector<int>> adj = vector<vector<int>>(boys, vector<int>{});\nfor (int boy = 0; boy < boys; boy++) {\n    for (int girl = 0; girl < girls; girl++) {\n        if (grid[boy][girl] == 1) {\n            adj[boy].push_back(girl);\n        }\n    }\n}\nvector<bool> taken = vector<bool>(girls, false);\nint invited = 0;\nfor (int boy = 0; boy < boys; boy++) {\n    for (int girl : adj[boy]) {\n        if (!taken[girl]) {\n            taken[girl] = true;\n            invited++;\n            break;\n        }\n    }\n}\nreturn invited;","lineMap":{"2":1,"3":2,"4":3,"5":4,"6":5,"7":6,"8":7,"9":11,"10":12,"11":13,"12":14,"13":15,"14":16,"15":17,"16":18,"17":22},"statementBundles":{"8":{"startLine":7,"endLine":10},"16":{"startLine":18,"endLine":21}}}}}},{"id":"greedy-cost","chapter":"The obvious way","kind":"case-probe","eyebrow":"Why it is wrong","title":"Why did greedy miss an invitation that was available?","summary":"Girl 1 stayed free, yet boy 1 ended up with nobody, so greedy returned a wrong, undersized answer.","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"greedy-stranded","state":{"graph":{"nodes":[{"id":"B0","label":"B0"},{"id":"B1","label":"B1"},{"id":"G0","label":"G0"},{"id":"G1","label":"G1"}],"edges":[["B0","G0"],["B0","G1"],["B1","G0"]],"current":"B1","highlighted":["G1"],"activeEdges":[["B0","G0"]]}}}]},"options":[{"id":"early-grab","label":"Boy 0 grabbed girl 0 first, the one girl boy 1 also needed","rationale":"Boy 0 had a spare option in girl 1, but he took girl 0 anyway and never reconsidered. Boy 1 had no spare, so the early grab cost an invitation that a swap would have saved.","isCorrect":true},{"id":"wrong-order","label":"The boys were processed in the wrong order","rationale":"Reordering only moves the conflict. Whichever boy grabs a shared girl first can still strand a later boy with no spare, unless an earlier choice can be revised.","isCorrect":false},{"id":"missing-edge","label":"An edge was missing from the grid","rationale":"Every 1 in the grid is accounted for. Both pairings exist; greedy just locked in a choice it should have been willing to undo.","isCorrect":false}],"answer":"Boy 0 took girl 0, the single girl boy 1 also needed, even though boy 0 could have invited girl 1. Greedy never revisits a placed match, so a fixable conflict becomes a lost invitation."},{"id":"augment-insight","chapter":"The idea","kind":"case-probe","eyebrow":"Find the move","title":"Boy 1 wants a girl boy 0 holds. What rescues the invitation?","summary":"Boy 1 can invite only girl 0, currently held by boy 0.","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"conflict","state":{"graph":{"nodes":[{"id":"B0","label":"B0"},{"id":"B1","label":"B1"},{"id":"G0","label":"G0"},{"id":"G1","label":"G1"}],"edges":[["B0","G0"],["B0","G1"],["B1","G0"]],"current":"B1","highlighted":["G0"],"activeEdges":[["B0","G0"]]}}}]},"options":[{"id":"reroute-owner","label":"Ask girl 0's current boy, boy 0, to move to another open girl","rationale":"Boy 0 still has girl 1 free. Moving boy 0 to girl 1 releases girl 0 for boy 1, so both invitations are accepted. The search hands the conflict to the current owner and lets him step aside.","isCorrect":true},{"id":"give-up","label":"Leave boy 1 unmatched, since his only girl is taken","rationale":"That is exactly greedy's mistake. The boy holding girl 0 can relocate, so a taken girl is not a dead end yet.","isCorrect":false},{"id":"drop-boy0","label":"Cancel boy 0's invitation entirely and give girl 0 to boy 1","rationale":"Canceling boy 0 trades one invitation for another and never grows the total. The win comes from relocating boy 0 to a free girl, not abandoning his match.","isCorrect":false}],"answer":"Ask girl 0's owner, boy 0, to relocate. Boy 0 still has girl 1 open, so he moves there and frees girl 0 for boy 1. Both invitations are accepted."},{"id":"augmenting-invariant","chapter":"The idea","kind":"case-probe","eyebrow":"Name the rule","title":"When can a boy be added without canceling anyone's invitation?","summary":"A relocation can cascade: the boy you ask to move may himself have to ask his own girl's current boy to move.","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"rerouted","state":{"graph":{"nodes":[{"id":"B0","label":"B0"},{"id":"B1","label":"B1"},{"id":"G0","label":"G0"},{"id":"G1","label":"G1"}],"edges":[["B0","G1"],["B1","G0"]],"activeEdges":[["B0","G1"],["B1","G0"]]}}}]},"options":[{"id":"chain-to-free","label":"When the chain of relocations ends at a girl nobody has invited","rationale":"Each boy asked to move either finds a free girl or passes the request along his own edges. If the chain ever reaches a girl no boy holds, every boy on it shifts by one and the count grows by exactly one.","isCorrect":true},{"id":"any-edge","label":"Whenever the new boy has at least one compatible girl","rationale":"Having an edge is not enough. If every girl he can reach is held by a boy who also has nowhere to move, the chain dead-ends and the count cannot grow.","isCorrect":false},{"id":"free-right-now","label":"Only when one of his girls is free right now","rationale":"An immediately free girl is the easy case, but a fully taken set of options can still open up if its owners can relocate down the chain. Requiring a free girl up front misses those.","isCorrect":false}],"answer":"When the chain of relocations reaches a girl nobody holds. Every boy along that chain shifts by one, freeing the girl the new boy needs and lifting the count by one."},{"id":"approach-selection","kind":"choice","source":"approach-selection","chapter":"The idea","title":"Which search should each boy run?","eyebrow":"Pick the route","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"graph","state":{"graph":{"nodes":[{"id":"B0","label":"B0"},{"id":"B1","label":"B1"},{"id":"G0","label":"G0"},{"id":"G1","label":"G1"}],"edges":[["B0","G0"],["B0","G1"],["B1","G0"]]}}}]},"selection":{"contract":"approach-selection-v1","question":"Which approach should we implement?","decisionPrompt":"Choose the approach whose state and complexity match the problem constraints.","approaches":[{"id":"greedy-free-only","name":"Take only free girls","summary":"Give each boy the first currently free compatible girl.","decisionReason":"It pairs boy 0 with girl 0 and then strands boy 1, because it never revisits a placed match. The conflict the relocation chain solves is exactly what this approach drops.","complexity":{"time":"O(m*n)","space":"O(n)"},"tradeoffs":["Runs in O(m*n) time and uses O(n) space."],"isOptimal":false},{"id":"augmenting-path","name":"Augmenting-path matching","summary":"Run a DFS from each boy that follows the relocation chain, moving owners aside until it reaches a free girl.","decisionReason":"The DFS is the relocation chain made concrete: each boy either takes a free girl or asks an owner to move down his own edges. It recovers the invitations greedy loses.","complexity":{"time":"O(m * E)","space":"O(E + n)"},"tradeoffs":["Runs in O(m * E) time and uses O(E + n) space."],"isOptimal":true}]}},{"id":"dry-run-setup","chapter":"Trace","kind":"info","eyebrow":"Watch it move","title":"Run one search per boy","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"start","state":{"graph":{"nodes":[{"id":"B0","label":"B0"},{"id":"B1","label":"B1"},{"id":"G0","label":"G0"},{"id":"G1","label":"G1"}],"edges":[["B0","G0"],["B0","G1"],["B1","G0"]],"current":"B0"}}}]},"body":["Take grid = [[1,1],[1,0]]: boy 0 reaches girl 0 and girl 1, boy 1 reaches only girl 0. The first search is about to begin from boy 0, highlighted as current. No girl is held yet. Within one search, each girl is touched at most once. The search claims a free girl when it sees one, and when the girl is held, it asks her current boy to relocate down his own edges. Each boy starts his own search with a fresh record of touched girls, so an earlier search never blocks a later reroute.","Watch the accepted invitations, drawn bold, change as the second search reroutes the first."]},{"id":"trace","kind":"dry-run","source":"trace-example","chapter":"Trace","title":"Trace the rerouting search","eyebrow":"Trace the state","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"match-b0","state":{"graph":{"nodes":[{"id":"B0","label":"B0"},{"id":"B1","label":"B1"},{"id":"G0","label":"G0"},{"id":"G1","label":"G1"}],"edges":[["B0","G0"],["B0","G1"],["B1","G0"]],"current":"B0"}}},{"id":"b1-wants-g0","state":{"graph":{"nodes":[{"id":"B0","label":"B0"},{"id":"B1","label":"B1"},{"id":"G0","label":"G0"},{"id":"G1","label":"G1"}],"edges":[["B0","G0"],["B0","G1"],["B1","G0"]],"current":"B1","highlighted":["G0"],"activeEdges":[["B0","G0"]]}}},{"id":"reroute-b0","state":{"graph":{"nodes":[{"id":"B0","label":"B0"},{"id":"B1","label":"B1"},{"id":"G0","label":"G0"},{"id":"G1","label":"G1"}],"edges":[["B0","G0"],["B0","G1"],["B1","G0"]],"current":"B0","activeEdges":[["B0","G0"]]}}},{"id":"both-matched","state":{"graph":{"nodes":[{"id":"B0","label":"B0"},{"id":"B1","label":"B1"},{"id":"G0","label":"G0"},{"id":"G1","label":"G1"}],"edges":[["B0","G1"],["B1","G0"]],"activeEdges":[["B0","G1"],["B1","G0"]]}}}]},"beats":[{"id":"match-b0","title":"When boy 0's search runs first, which girl does he invite?","summary":"Nothing is matched yet. Boy 0 can reach girl 0 or girl 1.","prompt":"Boy 0 runs his search.","options":[{"id":"takes-g0","label":"He claims girl 0, the first free girl he reaches","rationale":"Both of boy 0's girls are free, so the search takes the first one it visits and records boy 0 as girl 0's owner.","isCorrect":true},{"id":"takes-both","label":"He claims both girl 0 and girl 1","rationale":"A boy can hold only one girl at a time. The search stops at the first girl it successfully claims.","isCorrect":false},{"id":"skips","label":"He waits to see if boy 1 needs girl 0","rationale":"The search has no foresight. Boy 0 claims a girl now, and a later search reroutes him if needed.","isCorrect":false}],"answer":"He claims girl 0, the first free girl he reaches, and becomes her owner."},{"id":"b1-wants-g0","title":"Boy 1 can reach only girl 0, and boy 0 holds her. What does the search do?","summary":"Boy 1's single edge points at girl 0, currently held by boy 0.","prompt":"Boy 1 runs his search.","options":[{"id":"ask-owner","label":"It asks girl 0's owner, boy 0, to find another girl","rationale":"A taken girl is not a dead end. The search recurses into the current owner to see whether that boy can relocate, which would free girl 0.","isCorrect":true},{"id":"fails","label":"It fails immediately, since girl 0 is taken","rationale":"That is the greedy mistake. The owner may have a spare girl, so the search tries to relocate him before giving up.","isCorrect":false},{"id":"evict","label":"It cancels boy 0's invitation and leaves him unmatched","rationale":"Canceling trades one invitation for another and never grows the total. The search relocates the owner instead of abandoning his match.","isCorrect":false}],"answer":"It recurses into boy 0, girl 0's owner, to ask whether boy 0 can move to a different girl."},{"id":"reroute-b0","title":"Boy 0 is asked to move. Where does he go?","summary":"Boy 0 currently holds girl 0, the girl that caused the conflict. His search now looks past girl 0 for somewhere else to land.","prompt":"Boy 0 looks for a new girl.","options":[{"id":"to-g1","label":"Boy 0 moves to girl 1, freeing girl 0 for boy 1","rationale":"Girl 1 is free, so boy 0 relocates there. That releases girl 0, the chain reaches a girl nobody holds, and the relocation succeeds back up to boy 1.","isCorrect":true},{"id":"stuck","label":"Boy 0 has nowhere to go, so the reroute fails","rationale":"Boy 0 still has girl 1 open, so he does have somewhere to go. The chain ends at a free girl.","isCorrect":false},{"id":"back-g0","label":"Boy 0 stays on girl 0 and boy 1 takes girl 1","rationale":"Boy 1 has no edge to girl 1, so he cannot invite her. The relocation has to move boy 0, not boy 1.","isCorrect":false}],"answer":"Boy 0 moves to the free girl 1. That frees girl 0, and boy 1 claims her, so the chain lifts the count to two."},{"id":"both-matched","title":"After both searches finish, what is the accepted count?","prompt":"Read the bold matched edges off the graph.","options":[{"id":"two","label":"2: boy 0 with girl 1 and boy 1 with girl 0","rationale":"The reroute paired both boys, so two invitations are accepted. This beats greedy's one.","isCorrect":true},{"id":"one","label":"1, the same as greedy","rationale":"The relocation chain rescued boy 1, so the count is two, not one. That is the whole point of rerouting.","isCorrect":false},{"id":"three","label":"3, every node is used","rationale":"There are only two girls, so at most two invitations can be accepted. The answer is capped by the smaller side.","isCorrect":false}],"answer":"Two: boy 0 with girl 1 and boy 1 with girl 0. The relocation grew the count past what greedy reached."}]},{"id":"seen-pitfall","chapter":"Trace","kind":"pitfall","eyebrow":"Spot the trap","title":"Can one visited marker serve every boy's search?","summary":"Marking each girl visited stops a single search from looping forever. If that marker is allocated once and reused across all boys, every test with one search per conflict still passes. Watch what happens when a later search needs a girl an earlier search already touched.","workspacePanel":"trace","pitfall":"The seen array is created once, outside the per-boy loop, so girls touched by boy 0's search stay marked when boy 1 searches.","whyItMatters":"A girl marked during an earlier search looks visited to a later one, so the later search skips her and reports no reroute even when one exists. Allocate fresh seen state inside the loop for each boy's search so every root starts with a clean view.","negativeTrace":{"contract":"negative-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"def maximumInvitations(grid: list[list[int]]) -> int:\n    boys = len(grid)\n    girls = len(grid[0])\n    adj: list[list[int]] = [[] for _ in range(boys)]\n    for boy in range(boys):\n        for girl in range(girls):\n            if grid[boy][girl] == 1:\n                adj[boy].append(girl)\n    match = [-1] * girls\n    def dfs(boy: int, seen: list[bool]) -> bool:\n        for girl in adj[boy]:\n            if seen[girl]:\n                continue\n            seen[girl] = True\n            if match[girl] == -1 or dfs(match[girl], seen):\n                match[girl] = boy\n                return True\n        return False\n    seen = [False] * girls\n    invited = 0\n    for boy in range(boys):\n        if dfs(boy, seen):\n            invited += 1\n    return invited","steps":[{"id":"b0-marks-g0","title":"Boy 0's search marks girl 0 and claims her","codeLine":22,"summary":"Boy 0 visits girl 0, marks her seen, and takes her. The shared seen array now holds that mark.","state":{"graph":{"nodes":[{"id":"B0","label":"B0"},{"id":"B1","label":"B1"},{"id":"G0","label":"G0"},{"id":"G1","label":"G1"}],"edges":[["B0","G0"],["B0","G1"],["B1","G0"]],"current":"B0","highlighted":["G0"],"activeEdges":[["B0","G0"]]}}},{"id":"b1-skips-g0","title":"Boy 1 sees girl 0 already marked and skips her","codeLine":22,"summary":"Girl 0 is still marked from boy 0's search. Boy 1's only edge points at girl 0, who now looks visited, so the search skips her.","state":{"graph":{"nodes":[{"id":"B0","label":"B0"},{"id":"B1","label":"B1"},{"id":"G0","label":"G0"},{"id":"G1","label":"G1"}],"edges":[["B0","G0"],["B0","G1"],["B1","G0"]],"current":"B1","highlighted":["G0"]}}},{"id":"wrong-answer","title":"It returns 1","codeLine":24,"summary":"Boy 1's search never asks boy 0 to relocate, because girl 0 looked visited. The reroute that should have paired both boys never happens, so this returns 1 instead of 2.","state":{"graph":{"nodes":[{"id":"B0","label":"B0"},{"id":"B1","label":"B1"},{"id":"G0","label":"G0"},{"id":"G1","label":"G1"}],"edges":[["B0","G0"],["B0","G1"],["B1","G0"]],"activeEdges":[["B0","G0"]]}}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"const boys = grid.length;\nconst girls = grid[0].length;\nconst adj = Array.from({ length: boys }, () => []);\nfor (let boy = 0; boy < boys; boy++) {\n    for (let girl = 0; girl < girls; girl++) {\n        if (grid[boy][girl] === 1) {\n            adj[boy].push(girl);\n        }\n    }\n}\nconst match = Array(girls).fill(-1);\nfunction dfs(boy, seen) {\n    for (const girl of adj[boy]) {\n        if (seen[girl]) {\n            continue;\n        }\n        seen[girl] = true;\n        if (match[girl] === -1 || dfs(match[girl], seen)) {\n            match[girl] = boy;\n            return true;\n        }\n    }\n    return false;\n}\nconst seen = Array(girls).fill(false);\nlet invited = 0;\nfor (let boy = 0; boy < boys; boy++) {\n    if (dfs(boy, seen)) {\n        invited++;\n    }\n}\nreturn invited;","lineMap":{"2":1,"3":2,"4":3,"5":4,"6":5,"7":6,"8":7,"9":11,"11":13,"12":14,"13":15,"14":17,"15":18,"16":19,"17":20,"18":23,"19":25,"20":26,"21":27,"22":28,"23":29,"24":32},"statementBundles":{"8":{"startLine":7,"endLine":10},"9":{"startLine":11,"endLine":12},"13":{"startLine":15,"endLine":16},"17":{"startLine":20,"endLine":22},"18":{"startLine":23,"endLine":24},"23":{"startLine":29,"endLine":31}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"const boys = grid.length;\nconst girls = grid[0].length;\nconst adj: Array<Array<number>> = Array.from({ length: boys }, () => []);\nfor (let boy = 0; boy < boys; boy++) {\n    for (let girl = 0; girl < girls; girl++) {\n        if (grid[boy][girl] === 1) {\n            adj[boy].push(girl);\n        }\n    }\n}\nconst match = Array(girls).fill(-1);\nfunction dfs(boy: number, seen: Array<boolean>): boolean {\n    for (const girl of adj[boy]) {\n        if (seen[girl]) {\n            continue;\n        }\n        seen[girl] = true;\n        if (match[girl] === -1 || dfs(match[girl], seen)) {\n            match[girl] = boy;\n            return true;\n        }\n    }\n    return false;\n}\nconst seen = Array(girls).fill(false);\nlet invited = 0;\nfor (let boy = 0; boy < boys; boy++) {\n    if (dfs(boy, seen)) {\n        invited++;\n    }\n}\nreturn invited;","lineMap":{"2":1,"3":2,"4":3,"5":4,"6":5,"7":6,"8":7,"9":11,"11":13,"12":14,"13":15,"14":17,"15":18,"16":19,"17":20,"18":23,"19":25,"20":26,"21":27,"22":28,"23":29,"24":32},"statementBundles":{"8":{"startLine":7,"endLine":10},"9":{"startLine":11,"endLine":12},"13":{"startLine":15,"endLine":16},"17":{"startLine":20,"endLine":22},"18":{"startLine":23,"endLine":24},"23":{"startLine":29,"endLine":31}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"private static boolean dfs(int boy, List<Boolean> seen, List<List<Integer>> adj, List<Integer> match) {\n    for (Integer girl : adj.get(boy)) {\n        if (seen.get(girl)) {\n            continue;\n        }\n        seen.set(girl, true);\n        if ((match.get(girl) == -1 || dfs(match.get(girl), seen, adj, match))) {\n            match.set(girl, boy);\n            return true;\n        }\n    }\n    return false;\n}\n\nint boys = grid.size();\nint girls = grid.get(0).size();\nList<List<Integer>> adj = new ArrayList<>();\nfor (int i = 0; i < boys; i++) {\n    adj.add(new ArrayList<>());\n}\nfor (int boy = 0; boy < boys; boy++) {\n    for (int girl = 0; girl < girls; girl++) {\n        if (grid.get(boy).get(girl) == 1) {\n            adj.get(boy).add(girl);\n        }\n    }\n}\nList<Integer> match = new ArrayList<>();\nfor (int index = 0; index < girls; index++) {\n    match.add(-1);\n}\nList<Boolean> seen = new ArrayList<>();\nfor (int index = 0; index < girls; index++) {\n    seen.add(false);\n}\nint invited = 0;\nfor (int boy = 0; boy < boys; boy++) {\n    if (dfs(boy, seen, adj, match)) {\n        invited++;\n    }\n}\nreturn invited;","lineMap":{"2":15,"3":16,"4":17,"5":21,"6":22,"7":23,"8":24,"9":28,"11":2,"12":3,"13":4,"14":6,"15":7,"16":8,"17":9,"18":12,"19":32,"20":36,"21":37,"22":38,"23":39,"24":42},"statementBundles":{"4":{"startLine":17,"endLine":20},"8":{"startLine":24,"endLine":27},"9":{"startLine":28,"endLine":31},"13":{"startLine":4,"endLine":5},"17":{"startLine":9,"endLine":11},"18":{"startLine":12,"endLine":13},"19":{"startLine":32,"endLine":35},"23":{"startLine":39,"endLine":41}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"int boys = grid.Count;\nint girls = grid[0].Count;\nList<List<int>> adj = Enumerable.Range(0, boys).Select(_ => new List<int>()).ToList();\nfor (int boy = 0; boy < boys; boy++) {\n    for (int girl = 0; girl < girls; girl++) {\n        if (grid[boy][girl] == 1) {\n            adj[boy].Add(girl);\n        }\n    }\n}\nList<int> match = Enumerable.Repeat<int>(-1, girls).ToList();\nbool Dfs(int boy, List<bool> seen) {\n    foreach (int girl in adj[boy]) {\n        if (seen[girl]) {\n            continue;\n        }\n        seen[girl] = true;\n        if (match[girl] == -1 || Dfs(match[girl], seen)) {\n            match[girl] = boy;\n            return true;\n        }\n    }\n    return false;\n    return false;\n}\nList<bool> seen = Enumerable.Repeat<bool>(false, girls).ToList();\nint invited = 0;\nfor (int boy = 0; boy < boys; boy++) {\n    if (Dfs(boy, seen)) {\n        invited++;\n    }\n}\nreturn invited;","lineMap":{"2":1,"3":2,"4":3,"5":4,"6":5,"7":6,"8":7,"9":11,"11":13,"12":14,"13":15,"14":17,"15":18,"16":19,"17":20,"18":23,"19":26,"20":27,"21":28,"22":29,"23":30,"24":33},"statementBundles":{"8":{"startLine":7,"endLine":10},"9":{"startLine":11,"endLine":12},"13":{"startLine":15,"endLine":16},"17":{"startLine":20,"endLine":22},"18":{"startLine":23,"endLine":25},"23":{"startLine":30,"endLine":32}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"function<bool(int, vector<bool>&)> dfs;\n\nint boys = grid.size();\nint girls = grid[0].size();\nvector<vector<int>> adj = vector<vector<int>>(boys, vector<int>{});\nfor (int boy = 0; boy < boys; boy++) {\n    for (int girl = 0; girl < girls; girl++) {\n        if (grid[boy][girl] == 1) {\n            adj[boy].push_back(girl);\n        }\n    }\n}\nvector<int> match = vector<int>(girls, -1);\ndfs = [&]( int boy, vector<bool>& seen ) -> bool {\n    for (int girl : adj[boy]) {\n        if (seen[girl]) {\n            continue;\n        }\n        seen[girl] = true;\n        if ((match[girl] == -1 || dfs(match[girl], seen))) {\n            match[girl] = boy;\n            return true;\n        }\n    }\n    return false;\n};\nvector<bool> seen = vector<bool>(girls, false);\nint invited = 0;\nfor (int boy = 0; boy < boys; boy++) {\n    if (dfs(boy, seen)) {\n        invited++;\n    }\n}\nreturn invited;","lineMap":{"2":3,"3":4,"4":5,"5":6,"6":7,"7":8,"8":9,"9":13,"11":15,"12":16,"13":17,"14":19,"15":20,"16":21,"17":22,"18":25,"19":27,"20":28,"21":29,"22":30,"23":31,"24":34},"statementBundles":{"8":{"startLine":9,"endLine":12},"9":{"startLine":13,"endLine":14},"13":{"startLine":17,"endLine":18},"17":{"startLine":22,"endLine":24},"18":{"startLine":25,"endLine":26},"23":{"startLine":31,"endLine":33}}}}}},{"id":"edge-case-intro","chapter":"Edge cases","kind":"info","eyebrow":"Try to break it","title":"Which inputs could break this?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"graph","state":{"graph":{"nodes":[{"id":"B0","label":"B0"},{"id":"B1","label":"B1"},{"id":"G0","label":"G0"},{"id":"G1","label":"G1"}],"edges":[["B0","G1"],["B1","G0"]],"activeEdges":[["B0","G1"],["B1","G0"]]}}}]},"body":["Running one rerouting search per boy, with fresh seen state each time, accepted both invitations in the sample.","Before coding it, push on the inputs that stress how the count is seeded and how far one girl's ownership can stretch."]},{"id":"no-edges-edge","chapter":"Edge cases","kind":"case-probe","eyebrow":"Stress the rule","title":"What if the grid is all zeros?","summary":"Three boys, two girls, and not a single 1 in the grid.","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"graph","state":{"graph":{"nodes":[{"id":"B0","label":"B0"},{"id":"B1","label":"B1"},{"id":"B2","label":"B2"},{"id":"G0","label":"G0"},{"id":"G1","label":"G1"}],"edges":[]}}}]},"options":[{"id":"zero","label":"0, no invitation is possible","rationale":"Every boy's neighbor list is empty, so each search finds no girl to claim or reroute. The count never leaves zero.","isCorrect":true},{"id":"two","label":"2, capped by the smaller side","rationale":"The smaller side only caps the answer. With no compatible pairs there is nothing to accept, so the actual count is zero.","isCorrect":false},{"id":"three","label":"3, one per boy","rationale":"A boy only counts when his search succeeds. With no edges, no search succeeds, so none of the three are matched.","isCorrect":false}],"answer":"0. Every neighbor list is empty, so no search can claim or reroute a girl and the count stays zero."},{"id":"chain-reroute-edge","chapter":"Edge cases","kind":"case-probe","eyebrow":"Stress the rule","title":"Three boys all want girl 0 first. Can all three be accepted?","summary":"Three boys, three girls. Boy 0 reaches girl 0 and girl 1, boy 1 reaches girl 0 and girl 2, boy 2 reaches only girl 0.","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"graph","state":{"graph":{"nodes":[{"id":"B0","label":"B0"},{"id":"B1","label":"B1"},{"id":"B2","label":"B2"},{"id":"G0","label":"G0"},{"id":"G1","label":"G1"},{"id":"G2","label":"G2"}],"edges":[["B0","G0"],["B0","G1"],["B1","G0"],["B1","G2"],["B2","G0"]]}}}]},"options":[{"id":"all-three","label":"Yes, a chain of relocations frees girl 0 for boy 2","rationale":"Boy 2 needs girl 0. The search asks boy 0 to move to girl 1, and boy 1, if he held girl 0, to move to girl 2. Each owner has a spare, so the chain reaches free girls and all three are accepted.","isCorrect":true},{"id":"two-only","label":"No, boy 2 has only one edge, so he cannot be matched","rationale":"One edge is enough when the owner of that girl can relocate. Both earlier boys have spare girls, so the relocation chain clears girl 0 for boy 2.","isCorrect":false},{"id":"depends-order","label":"Only if the boys happen to be processed in a lucky order","rationale":"The rerouting search succeeds regardless of order, because it actively relocates owners rather than relying on them to have chosen well. The chain finds the free girls either way.","isCorrect":false}],"answer":"Yes. Boy 2's search pushes boy 0 toward girl 1 and boy 1 toward girl 2, and since each owner has a spare, the chain frees girl 0 and all three are accepted."},{"id":"ready-to-code","chapter":"Code","kind":"info","eyebrow":"Get ready to code","title":"Turn the rerouting rule into code","summary":"Watch one detail: each boy's search needs its own fresh record of which girls it has touched.","ctaLabel":"Start coding","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"graph","state":{"graph":{"nodes":[{"id":"B0","label":"B0"},{"id":"B1","label":"B1"},{"id":"G0","label":"G0"},{"id":"G1","label":"G1"}],"edges":[["B0","G0"],["B0","G1"],["B1","G0"]]}}}]},"body":["Group each boy's compatible girls into a neighbor list, and record for each girl which boy currently holds her, starting every girl unheld. Then run a search from every boy: he takes a free girl, or asks the current owner to relocate down the owner's own edges.","Give each boy's search a fresh visited record so an earlier search's marks never hide a reroute, and count one for every search that succeeds."]},{"id":"coding","kind":"coding","source":"coding-checkpoints","chapter":"Code","title":"Build the rerouting matcher","eyebrow":"Code the rule","summary":"Now build the rerouting matcher: turn each grid row into a neighbor list, start every girl owned by no one, write the search that takes a free girl or asks her owner to move down his own edges, then run one search per boy with fresh visited state and count the ones that land.","workspacePanel":"code","checkpoints":[{"id":"build-adj","title":"Build compatibility edges","description":"Convert each matrix row into the girls that boy can invite.","commonMistakes":["Scanning the raw matrix inside every DFS call","Dropping valid edges while building adjacency"],"hint":"Build `adj[boy]` from the columns where `grid[boy][girl] == 1`.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"bipartite-matching","fact":"builds_bipartite_adjacency_state","scope":"build-adj","readMode":"bipartite-matching-value-query-v1"}]},"semanticSpec":{"intent":"Build reusable boy-to-girl adjacency before running matching.","doneWhen":"Every 1 in the compatibility matrix becomes an edge in adjacency state.","shouldFailWhen":"The code never builds an adjacency structure from grid edges.","roles":["boy","girl","adjacency list"],"mustProve":["The solution builds bipartite adjacency state from compatible matrix entries."],"mustNotAccept":["Using an unrelated graph or ignoring zero entries."],"proofSnippets":[{"id":"py-maximum-invitations-build-adj","language":"python","code":"def maximumInvitations(grid):\n    adj = [[] for _ in range(len(grid))]\n    for boy in range(len(grid)):\n        for girl in range(len(grid[0])):\n            if grid[boy][girl] == 1:\n                adj[boy].append(girl)"}]}},{"id":"init-match","title":"Initialize the match state","description":"Create the array that records which boy is currently matched to each girl, using -1 for unmatched girls.","commonMistakes":["Sizing the match array by the number of boys instead of girls","Using a non-sentinel initial value that cannot distinguish unmatched girls"],"hint":"After building compatibility edges, initialize one slot per girl with -1 so DFS can tell whether a girl is unmatched or needs rerouting.","semanticSpec":{"intent":"Prepare the right-side ownership state used by augmenting-path DFS.","doneWhen":"This step is done when the code creates a match array with one entry per girl and initializes each entry to an unmatched sentinel.","shouldFailWhen":"This step should fail if the match state is missing, has the wrong size, or starts with values that look already matched.","roles":["right-side match state","unmatched sentinel","girl count"],"mustProve":["The match state has one slot for each girl.","Every slot starts as unmatched before DFS runs."],"mustNotAccept":["A match array sized by the number of boys.","A match state initialized with real boy ids before search starts."],"equivalentVariants":["Use -1, None, or another clear unmatched sentinel if the later DFS checks the same sentinel.","Name the match state match, owner, assigned, or any equivalent ownership variable."],"proofSnippets":[{"id":"py-maximum-invitations-init-match","language":"python","code":"def maximumInvitations(grid):\n    boys = len(grid)\n    girls = len(grid[0])\n    adj = [[] for _ in range(boys)]\n    for boy in range(boys):\n        for girl in range(girls):\n            if grid[boy][girl] == 1:\n                adj[boy].append(girl)\n    match = [-1] * girls"}]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"bipartite-matching","fact":"initializes_match_state","scope":"init-match","readMode":"bipartite-matching-value-query-v1"}]}},{"id":"dfs-match","title":"Implement augmenting DFS","description":"Claim a free girl or recursively reroute the boy currently matched to her.","commonMistakes":["Treating an occupied girl as permanently unavailable","Forgetting the visited guard inside DFS"],"hint":"A girl can be used if she is free or if her current match can move elsewhere.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"bipartite-matching","fact":"defines_augmenting_reroute_helper","scope":"dfs-match","readMode":"bipartite-matching-value-query-v1"}]},"semanticSpec":{"intent":"Define the augmenting-path helper that can reroute existing matches.","doneWhen":"DFS writes a match when a girl is free or when her current owner can be recursively rerouted.","shouldFailWhen":"The helper never tries to reroute current owners.","roles":["augmenting helper","match state","visited state"],"mustProve":["The solution defines an augmenting reroute helper."],"mustNotAccept":["A greedy helper that only accepts currently free girls."],"proofSnippets":[{"id":"py-maximum-invitations-dfs-match","language":"python","code":"def maximumInvitations(grid):\n    boys = len(grid)\n    girls = len(grid[0])\n    adj = [[] for _ in range(boys)]\n    for boy in range(boys):\n        for girl in range(girls):\n            if grid[boy][girl] == 1:\n                adj[boy].append(girl)\n    match = [-1] * girls\n    def dfs(boy, seen):\n        for girl in adj[boy]:\n            if seen[girl]:\n                continue\n            seen[girl] = True\n            if match[girl] == -1 or dfs(match[girl], seen):\n                match[girl] = boy\n                return True\n        return False"}]}},{"id":"match-and-return","title":"Run searches and return count","description":"Try one fresh visited-state DFS per boy and return the number of successful matches.","commonMistakes":["Reusing visited state across root searches","Returning the match array instead of the count"],"hint":"Create `seen` inside the outer loop, call DFS, and increment the answer only when it succeeds.","validation":{"type":"semantic","validator":"all","params":[{"type":"semantic","validator":"familyFact","params":[{"family":"bipartite-matching","fact":"runs_augmenting_search_with_initialized_match_state","scope":"match-and-return","readMode":"bipartite-matching-value-query-v1"}]},{"type":"semantic","validator":"familyFact","params":[{"family":"bipartite-matching","fact":"allocates_visited_per_root_search","scope":"reset-seen","readMode":"bipartite-matching-value-query-v1"}]},{"type":"semantic","validator":"familyFact","params":[{"family":"bipartite-matching","fact":"executes_augmenting_search_with_fresh_visited_state","scope":"reset-seen","readMode":"bipartite-matching-value-query-v1"}]},{"type":"semantic","validator":"familyFact","params":[{"family":"bipartite-matching","fact":"returns_matching_size_after_augmenting_search","scope":"match-and-return","readMode":"bipartite-matching-value-query-v1"}]}]},"semanticSpec":{"intent":"Run the matching search from each boy with fresh visited state and return the matching size.","doneWhen":"The outer loop allocates fresh visited state, runs DFS, updates the count, and returns that count after all boys are processed.","shouldFailWhen":"The code reuses visited state, omits the match count update, or returns before all searches finish.","roles":["fresh visited state","matching count","outer search loop"],"mustProve":["The solution runs augmenting searches with initialized match state and fresh per-root visited state.","The solution returns the final matching size."],"mustNotAccept":["A single shared visited array for every root search.","Returning unrelated state."],"proofSnippets":[{"id":"py-maximum-invitations-match-and-return","language":"python","code":"def maximumInvitations(grid):\n    boys = len(grid)\n    girls = len(grid[0])\n    adj = [[] for _ in range(boys)]\n    for boy in range(boys):\n        for girl in range(girls):\n            if grid[boy][girl] == 1:\n                adj[boy].append(girl)\n    match = [-1] * girls\n    def dfs(boy, seen):\n        for girl in adj[boy]:\n            if seen[girl]:\n                continue\n            seen[girl] = True\n            if match[girl] == -1 or dfs(match[girl], seen):\n                match[girl] = boy\n                return True\n        return False\n    invited = 0\n    for boy in range(boys):\n        seen = [False] * girls\n        if dfs(boy, seen):\n            invited += 1\n    return invited"}]}}]},{"id":"complete","kind":"complete","chapter":"Code","title":"You can see why rerouting wins","eyebrow":"Wrap up","summary":"Greedy stranded an invitation it could not undo; the rerouting search recovered it.","workspacePanel":"code","takeaways":[{"title":"Greedy never takes back an invitation","body":"One early grab of a shared girl can strand a later boy who had no spare."},{"title":"A chain of relocations accepts exactly one more boy","body":"A boy can still be accepted whenever a chain of relocations from his girls reaches a girl nobody holds."},{"title":"Each boy's search starts with a fresh visited record","body":"A girl marked by an earlier search would otherwise hide the very reroute a later search depends on."},{"title":"One search per boy costs O(m * E) time","body":"It uses O(E + n) space, and the count can never exceed the smaller side."}],"nextAction":"Submit runs your solution against every test case."}],"slidesOrigin":"authored"},"version":1}
