Skip to content

Instantly share code, notes, and snippets.

@cywang117
Created August 5, 2020 02:18
Show Gist options
  • Save cywang117/0f79e48a47b7f2de503a598590b75c98 to your computer and use it in GitHub Desktop.
Save cywang117/0f79e48a47b7f2de503a598590b75c98 to your computer and use it in GitHub Desktop.
// - 2D grid map of 1's & 0's - 1 = land, 0 = water (strings)
// - count number of islands
// All 4 edges of the grid are considered water
/*
Input: grid = [
["1","1","1","1","0"],
["1","1","0","1","0"],
["1","1","0","0","0"],
["0","0","0","0","0"]
]
// 2 islands
[
["1","0","1","1","0"],
["1","1","0","1","0"],
["1","1","0","0","0"],
["0","0","0","0","0"]
]
// 2 islands
[
["1","1","0","1","0"],
["1","1","0","1","0"],
["1","1","0","0","0"],
["0","0","0","0","0"]
]
Output: 1
*/
/*
Output: number of islands in grid (integer, >= 0)
Input: matrix of 0's & 1's (strings) representing a block of land & water
Constraints: n by m grid, no irregular grids, O(?) time, O(?) space
Edge cases: [] => 0, [[]] => 0,
*/
// Island:
// - surrounded on all sides by water (0)
// - surrounded on n sides by 0's, and on 4-n sides by an edge
// Pseudocode:
// Keep a record of which cells in the grid have been visited already
// Track the count of islands thus far, 0 initially
// For each row of cells in grid
// If first row, record positions of land cells
// Else not first row:
// For each cell in row
// Compare the position of the current cell, if it's land, to recorded positions
// As long the current cell is a land cell, keep the recorded position as is
// Else check the previous row's record for continuous land: (example at position 2, need to check if 1, 2, 3 all exist as records in recorded positions) (position - 1, position, position + 1 all exist in recorded positions)
// If exists, remove the current position from recorded positions (prepare for next row)
// Else
// 0, 1, 2, 3
//
// Return the count
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment