Skip to content

Prepare For Coder Interview – Denny

  • Basic
  • Medium
  • Hard
  • Architect
  • Life

LeetCode: Number of Islands

Posted on January 22, 2018July 26, 2020 by braindenny

Number of Islands



Similar Problems:

  • Island City
  • Series: Island & Follow-up
  • CheatSheet: Leetcode For Code Interview
  • CheatSheet: Common Code Problems & Follow-ups
  • Tag: #graph, #dfs, #bfs, #island

Given a 2d grid map of ‘1’s (land) and ‘0’s (water), count the number of islands. An island 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.

Example 1:

11110
11010
11000
00000
Answer: 1
Example 2:

11000
11000
00100
00011
Answer: 3

Github: code.dennyzhang.com

Credits To: leetcode.com

Leave me comments, if you have better ways to solve.


## https://code.dennyzhang.com/number-of-islands
class Solution(object):
    ## Basic Ideas: Avoid duplicate counting.
    ##   Mark all adjacent 1 to X. Thus we can avoid counting one the same island multiple times.
    ##
    ## Complexity: Time O(m*n), Space O(1)
    def numIslands(self, grid):
        """
        :type grid: List[List[str]]
        :rtype: int
        """
        self.row_count = len(grid)
        if self.row_count == 0: return 0
        self.col_count = len(grid[0])

        res = 0
        for i in xrange(self.row_count):
            for j in xrange(self.col_count):
                if grid[i][j] == '1':
                    res += 1
                    self.DFSMark(grid, i, j)
        return res

    def DFSMark(self, grid, i, j):
        if i < 0 or i >= self.row_count \
            or j < 0 or j >= self.col_count:
            return

        # stop digging, if not '1'
        if grid[i][j] != '1': return

        grid[i][j] = 'X'
        # mark four positions in a recursive way
        self.DFSMark(grid, i-1, j)
        self.DFSMark(grid, i+1, j)
        self.DFSMark(grid, i, j-1)
        self.DFSMark(grid, i, j+1)
linkedin
github
slack

Post Views: 4
Posted in BasicTagged #codetemplate, #dfs, #graph, island

Post navigation

LeetCode: Unique Letter String
Review: Heap Problems

Leave a Reply Cancel reply

Your email address will not be published.

Tags

#array #backtracking #bfs #binarytree #bitmanipulation #blog #classic #codetemplate #combination #dfs #dynamicprogramming #game #graph #greedy #heap #inspiring #interval #linkedlist #manydetails #math #palindrome #recursive #slidingwindow #stack #string #subarray #trie #twopointer #twosum binarysearch editdistance hashmap intervaldp knapsack monotone oodesign presum rectangle redo review rotatelist series sql treetraversal unionfind

Recent Posts

  • a
  • a
  • a
  • a
  • a

Recent Comments

    Archives

    Categories

    • Amusing
    • Basic
    • Easy
    • Hard
    • Life
    • Medium
    • Resource
    • Review
    • Series
    • Uncategorized
    Proudly powered by WordPress | Theme: petals by Aurorum.