<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:
        # Classic dfs problem

        def dfs(i,j,grid,visited):
            visited.add((i,j))
            # Reached end of possible island
            if grid[i][j] == '0':
                visited.remove((i,j))
                return
            
            # DFS through all 4 neighbours
            if j+1<=len(grid[0])-1 and (i,j+1) not in visited:
                dfs(i,j+1,grid,visited)
            if j-1>=0 and (i,j-1) not in visited:
                dfs(i,j-1,grid,visited)
            if i+1<=len(grid)-1 and (i+1,j) not in visited:
                dfs(i+1,j,grid,visited)
            if i-1>=0 and (i-1,j) not in visited:
                dfs(i-1,j,grid,visited)
            return

        # Iterate through grid and use visited set to check if poisition has been visited and if gridValue == 1

        # Null Check
        if not grid:
            return 0

        numRows = len(grid)
        numCols = len(grid[0])
        visited = set()
        numIslands = 0
        for i in range(numRows):
            for j in range(numCols):
                if (i,j) not in visited:
                    if grid[i][j] == '1':
                        numIslands += 1
                        dfs(i,j,grid,visited)
        

        return numIslands
25316