<p>Given an <code>m x n</code> 2D binary grid <code>grid</code> which represents a map of <code>&#39;1&#39;</code>s (land) and <code>&#39;0&#39;</code>s (water), return <em>the number of islands</em>.</p>

<p>An <strong>island</strong> is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> grid = [
  [&quot;1&quot;,&quot;1&quot;,&quot;1&quot;,&quot;1&quot;,&quot;0&quot;],
  [&quot;1&quot;,&quot;1&quot;,&quot;0&quot;,&quot;1&quot;,&quot;0&quot;],
  [&quot;1&quot;,&quot;1&quot;,&quot;0&quot;,&quot;0&quot;,&quot;0&quot;],
  [&quot;0&quot;,&quot;0&quot;,&quot;0&quot;,&quot;0&quot;,&quot;0&quot;]
]
<strong>Output:</strong> 1
</pre>

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

<pre>
<strong>Input:</strong> grid = [
  [&quot;1&quot;,&quot;1&quot;,&quot;0&quot;,&quot;0&quot;,&quot;0&quot;],
  [&quot;1&quot;,&quot;1&quot;,&quot;0&quot;,&quot;0&quot;,&quot;0&quot;],
  [&quot;0&quot;,&quot;0&quot;,&quot;1&quot;,&quot;0&quot;,&quot;0&quot;],
  [&quot;0&quot;,&quot;0&quot;,&quot;0&quot;,&quot;1&quot;,&quot;1&quot;]
]
<strong>Output:</strong> 3
</pre>

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

<ul>
	<li><code>m == grid.length</code></li>
	<li><code>n == grid[i].length</code></li>
	<li><code>1 &lt;= m, n &lt;= 300</code></li>
	<li><code>grid[i][j]</code> is <code>&#39;0&#39;</code> or <code>&#39;1&#39;</code>.</li>
</ul>

class Solution:
    def numIslands(self, grid: List[List[str]]) -> int:
        m = len(grid)
        n = len(grid[0])
        island = [[0 for _ in range(n)] for _ in range(m)]
        island_idx = 0
        intersection = set()

        prev_node = 0
        upper_node = 0
        for i in range(m):
            for j in range(n):
                node = grid[i][j]
                if i > 0:
                    upper_node = island[i-1][j]
                else:
                    upper_node = 0
                if j > 0:
                    prev_node = island[i][j-1]
                else:
                    prev_node = 0
                
                if node == "1":
                    if prev_node == 0:
                        island_idx += 1
                    
                    island[i][j] = island_idx
                    if upper_node != 0 and upper_node < island_idx:
                        intersection.add((island_idx, upper_node))

        print(island)
        print(island_idx, intersection)
        from collections import deque, defaultdict

        # 그래프 구성: 인접 리스트로 표현
        graph = defaultdict(list)
        for a, b in intersection:
            graph[a].append(b)
            graph[b].append(a)

        # BFS를 사용하여 주어진 노드와 연결된 노드들 중 가장 작은 값을 찾기
        def find_smallest_connected(graph, start):
            queue = deque([start])
            visited = set([start])
            smallest = start  # 주어진 노드를 초기값으로 설정
            
            while queue:
                node = queue.popleft()
                
                # 현재 노드와 비교해 더 작은 노드를 찾기
                smallest = min(smallest, node)
                
                # 연결된 노드를 탐색
                for neighbor in graph[node]:
                    if neighbor not in visited:
                        visited.add(neighbor)
                        queue.append(neighbor)
            
            return smallest
        
        nums = 0
        for i in range(island_idx):
            s = find_smallest_connected(graph, i+1)
            if s == i+1:
                nums += 1
        # nums = island_idx - len(set([a for (a, b) in intersection]))

        return nums

25448