Approach
Depth-first search
For Maximum Students Taking Exam, the implementation follows one branch at a time, making it suitable for components, trees, backtracking, or dependency exploration.
- Define the state carried into one recursive or stack frame.
- Mark or choose the current state before exploring children.
- Combine child results or undo the choice when the branch finishes.
Code notes
- 37 lines of Python from the credited upstream file 1349.py.
- The implementation visibly relies on sequence storage.
- No explicit loop blocks detected, together with recursive traversal.
Complexity
Count unique states for graph traversal; for backtracking, count the branching factor and maximum depth.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution:2 def maxStudents(self, seats: list[list[str]]) -> int:3 m = len(seats)4 n = len(seats[0])5 DIRS = ((-1, -1), (0, -1), (1, -1), (-1, 1), (0, 1), (1, 1))6 seen = [[0] * n for _ in range(m)]7 match = [[-1] * n for _ in range(m)]8 9 def dfs(i: int, j: int, sessionId: int) -> int:10 for dx, dy in DIRS:11 x = i + dx12 y = j + dy13 if x < 0 or x == m or y < 0 or y == n:14 continue15 if seats[x][y] != '.' or seen[x][y] == sessionId:16 continue17 seen[x][y] = sessionId18 if match[x][y] == -1 or dfs(*divmod(match[x][y], n), sessionId):19 match[x][y] = i * n + j20 match[i][j] = x * n + y21 return 122 return 023 24 def hungarian() -> int:25 count = 026 for i in range(m):27 for j in range(n):28 if seats[i][j] == '.' and match[i][j] == -1:29 sessionId = i * n + j30 seen[i][j] = sessionId31 count += dfs(i, j, sessionId)32 return count33 34 return sum(seats[i][j] == '.'35 for i in range(m)36 for j in range(n)) - hungarian()37