<p>Given a <code>m&nbsp;* n</code>&nbsp;matrix <code>seats</code>&nbsp;&nbsp;that represent seats distributions&nbsp;in a classroom.&nbsp;If a seat&nbsp;is&nbsp;broken, it is denoted by <code>&#39;#&#39;</code> character otherwise it is denoted by a <code>&#39;.&#39;</code> character.</p>

<p>Students can see the answers of those sitting next to the left, right, upper left and upper right, but he cannot see the answers of the student sitting&nbsp;directly in front or behind him. Return the <strong>maximum </strong>number of students that can take the exam together&nbsp;without any cheating being possible.</p>

<p>Students must be placed in seats in good condition.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>
<img height="200" src="https://assets.leetcode.com/uploads/2020/01/29/image.png" width="339" />
<pre>
<strong>Input:</strong> seats = [[&quot;#&quot;,&quot;.&quot;,&quot;#&quot;,&quot;#&quot;,&quot;.&quot;,&quot;#&quot;],
&nbsp;               [&quot;.&quot;,&quot;#&quot;,&quot;#&quot;,&quot;#&quot;,&quot;#&quot;,&quot;.&quot;],
&nbsp;               [&quot;#&quot;,&quot;.&quot;,&quot;#&quot;,&quot;#&quot;,&quot;.&quot;,&quot;#&quot;]]
<strong>Output:</strong> 4
<strong>Explanation:</strong> Teacher can place 4 students in available seats so they don&#39;t cheat on the exam. 
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> seats = [[&quot;.&quot;,&quot;#&quot;],
&nbsp;               [&quot;#&quot;,&quot;#&quot;],
&nbsp;               [&quot;#&quot;,&quot;.&quot;],
&nbsp;               [&quot;#&quot;,&quot;#&quot;],
&nbsp;               [&quot;.&quot;,&quot;#&quot;]]
<strong>Output:</strong> 3
<strong>Explanation:</strong> Place all students in available seats. 

</pre>

<p><strong class="example">Example 3:</strong></p>

<pre>
<strong>Input:</strong> seats = [[&quot;#&quot;,&quot;.&quot;,&quot;<strong>.</strong>&quot;,&quot;.&quot;,&quot;#&quot;],
&nbsp;               [&quot;<strong>.</strong>&quot;,&quot;#&quot;,&quot;<strong>.</strong>&quot;,&quot;#&quot;,&quot;<strong>.</strong>&quot;],
&nbsp;               [&quot;<strong>.</strong>&quot;,&quot;.&quot;,&quot;#&quot;,&quot;.&quot;,&quot;<strong>.</strong>&quot;],
&nbsp;               [&quot;<strong>.</strong>&quot;,&quot;#&quot;,&quot;<strong>.</strong>&quot;,&quot;#&quot;,&quot;<strong>.</strong>&quot;],
&nbsp;               [&quot;#&quot;,&quot;.&quot;,&quot;<strong>.</strong>&quot;,&quot;.&quot;,&quot;#&quot;]]
<strong>Output:</strong> 10
<strong>Explanation:</strong> Place students in available seats in column 1, 3 and 5.
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>seats</code>&nbsp;contains only characters&nbsp;<code>&#39;.&#39;<font face="sans-serif, Arial, Verdana, Trebuchet MS">&nbsp;and</font></code><code>&#39;#&#39;.</code></li>
	<li><code>m ==&nbsp;seats.length</code></li>
	<li><code>n ==&nbsp;seats[i].length</code></li>
	<li><code>1 &lt;= m &lt;= 8</code></li>
	<li><code>1 &lt;= n &lt;= 8</code></li>
</ul>

class Solution:
    def maxStudents(self, seats: List[List[str]]) -> int:
        m = len(seats)
        n = len(seats[0])
        total_seats = sum(row.count('.') for row in seats)
        source = m * n
        sink = source + 1
        g = MCFGraph(m * n + 2)
        for col in range(0, n, 2):
            for row in range(m):
                if seats[row][col] == '.':
                    g.add_edge(source, row * n + col, 1, 0)
                    for dy, dx in (-1, -1), (0, -1), (1, -1), (1, 1), (0, 1), (-1, 1):
                        ny, nx = row + dy, col + dx
                        if 0 <= ny < m and 0 <= nx < n and seats[ny][nx] == '.':
                            g.add_edge(row * n + col, ny * n + nx, 1, 0)
        for col in range(1, n, 2):
            for row in range(m):
                if seats[row][col] == '.':
                    g.add_edge(row * n + col, sink, 1, 0)
        # I need to find the minimum vertex cover (MVC).
        # MVC is the minimum number of nodes that I need to remove
        # in order to disconnect even column seats from odd seats.
        # This minimum number of nodes can be found by finding maximum
        # number of edges that connect even to odd without sharing vertices.
        # Not sharing vertices is important, I want to remove as few nodes 
        # as possible to disconnect the even and odds.
        # If you do not remove one node from each edge in the maximum matching, 
        # there will still be connections between the even and odd seats.
        # This means that the two sets (even and odd) will remain connected via these edges.
        # If you remove one node from each of those edges, you can disconnect
        # the even and odd seats. 
        # Remove E:
        # E -- O
        #   \    \
        #     O -- SINK
        # Remove O:
        # E -- O -- SINK
        #    /
        # E /
        # Removing the critical seat disrupts the flow from even to odd.
        # From an edge in maximum matching, I want to remove the "junction" node, 
        # the node that blocks the most paths to the sink.
        # If I remove a node from each match and still have flow from even to odd, 
        # that would mean that I didn't find the max flow. Max flow guarantees
        # that I do not have any other path from even to odd.
        return total_seats - g.flow(source, sink)[0]
        
class MCFGraph:
    def __init__(self, num_nodes: int) -> None:
        self._n = num_nodes
        self._g: List[List[MCFGraph._Edge]] = [[] for _ in range(num_nodes)]
        self._edges: List[MCFGraph._Edge] = []

    class Edge(NamedTuple):
        src: int
        dst: int
        cap: int
        flow: int
        cost: int
        idx: Optional[int]

    class _Edge:
        def __init__(self, dst: int, cap: int, cost: int, idx: Optional[int]) -> None:
            self.dst = dst
            self.cap = cap
            self.cost = cost
            self.rev: Optional[MCFGraph._Edge] = None
            self.idx = idx
            self.original_cap = cap

    def add_edge(self, src: int, dst: int, cap: int, cost: int, idx: int = None) -> int:
        assert 0 <= src < self._n
        assert 0 <= dst < self._n
        assert 0 <= cap
        m = len(self._edges)
        e = MCFGraph._Edge(dst, cap, cost, idx)
        re = MCFGraph._Edge(src, 0, -cost, idx)
        e.rev = re
        re.rev = e
        self._g[src].append(e)
        self._g[dst].append(re)
        self._edges.append(e)
        return m

    def reset(self) -> None:
        """Reset all edges to their original capacities."""
        for e in self._edges:
            e.cap = e.original_cap
            e.rev.cap = 0

    def get_edge(self, i: int) -> Edge:
        assert 0 <= i < len(self._edges)
        e = self._edges[i]
        re = cast(MCFGraph._Edge, e.rev)
        return MCFGraph.Edge(
            re.dst,
            e.dst,
            e.cap + re.cap,
            re.cap,
            e.cost,
            e.idx
        )

    def get_flow_edges(self) -> List[Edge]:
        edges = []
        for edge in self.edges():
            if edge.flow:
                edges.append(edge)
        return edges

    def edges(self) -> List[Edge]:
        return [self.get_edge(i) for i in range(len(self._edges))]

    def flow(self, s: int, t: int, flow_limit: Optional[int] = None) -> Tuple[int, int]:
        return self.slope(s, t, flow_limit)[-1]

    def slope(self, s: int, t: int, flow_limit: Optional[int] = None) -> List[Tuple[int, int]]:
        assert 0 <= s < self._n
        assert 0 <= t < self._n
        if flow_limit is None:
            flow_limit = cast(int, sum(e.cap for e in self._g[s]))

        dual = [0] * self._n
        prev: List[Optional[Tuple[int, MCFGraph._Edge]]] = [None] * self._n

        def refine_dual() -> bool:
            pq = [(0, s)]
            visited = [False] * self._n
            dist: List[Optional[int]] = [None] * self._n
            dist[s] = 0
            while pq:
                dist_v, v = heappop(pq)
                if visited[v]:
                    continue
                visited[v] = True
                if v == t:
                    break
                dual_v = dual[v]
                for e in self._g[v]:
                    w = e.dst
                    if visited[w] or e.cap == 0:
                        continue
                    reduced_cost = e.cost - dual[w] + dual_v
                    new_dist = dist_v + reduced_cost
                    dist_w = dist[w]
                    if dist_w is None or new_dist < dist_w:
                        dist[w] = new_dist
                        prev[w] = v, e
                        heappush(pq, (new_dist, w))
            else:
                return False
            dist_t = dist[t]
            for v in range(self._n):
                if visited[v]:
                    dual[v] -= cast(int, dist_t) - cast(int, dist[v])
            return True

        flow = 0
        cost = 0
        prev_cost_per_flow: Optional[int] = None
        result = [(flow, cost)]
        while flow < flow_limit:
            if not refine_dual():
                break
            f = flow_limit - flow
            v = t
            while prev[v] is not None:
                u, e = cast(Tuple[int, MCFGraph._Edge], prev[v])
                f = min(f, e.cap)
                v = u
            v = t
            while prev[v] is not None:
                u, e = cast(Tuple[int, MCFGraph._Edge], prev[v])
                e.cap -= f
                assert e.rev is not None
                e.rev.cap += f
                v = u
            c = -dual[s]
            flow += f
            cost += f * c
            if c == prev_cost_per_flow:
                result.pop()
            result.append((flow, cost))
            prev_cost_per_flow = c
        return result

    def find_min_cut(self, s: int, t: int) -> List[Tuple[int, int]]:
        """
        Finds the edges in the minimum cut of the flow network.

        Args:
            s: The source node index.
            t: The sink node index.

        Returns:
            A list of edges in the minimum cut.
        """
        self.flow(s, t)
        reachable = set()
        queue = deque([s])
        reachable.add(s)
        while queue:
            node = queue.popleft()
            for edge in self._g[node]:
                if edge.cap > 0 and edge.dst not in reachable:
                    reachable.add(edge.dst)
                    queue.append(edge.dst)
        min_cut_edges = []
        for u in range(self._n):
            if u in reachable:
                for edge in self._g[u]:
                    if edge.cap == 0 and edge.dst not in reachable:
                        min_cut_edges.append((u, edge.dst))
        return min_cut_edges

    def dijkstra(self, src: int, dst: Optional[int] = None) -> Dict[int, int]:
        """Compute the shortest path distances from the source node to all other nodes in the graph."""
        dist = defaultdict(lambda: inf)
        dist[src] = 0
        h = [(0, src)]
        while h:
            current_dist, u = heapq.heappop(h)
            if current_dist > dist[u]:
                continue
            if u == dst:
                return dist
            for edge in self._g[u]:
                if edge.cap > 0:
                    v = edge.dst
                    new_dist = current_dist + edge.cost
                    if new_dist < dist[v]:
                        dist[v] = new_dist
                        heapq.heappush(h, (new_dist, v))
        return dist
52