r/csinterviewproblems • u/zhay • Dec 18 '15
Count number of islands
Given a matrix of 0s and 1s, where 0 represents water and 1 represents land, count the number of islands. Two pieces of land are connected if they are vertically or horizontally touching. Two pieces of land that are diagonal from each other are not touching.
e.g.:
Input
0 1 1 0 0 0 1
0 1 0 0 1 1 0
0 1 1 0 0 1 0
0 0 0 0 0 0 0
0 1 1 1 1 1 0Output
4Bonus: Can you solve this in constant space? Note: the recursive stack is considered extra space, and modifying the matrix at any time is prohibited.
9
Upvotes
3
u/WarDEagle Dec 19 '15 edited Dec 19 '15
Ok, so it seems as though the idea here is to interpret the matrix as an adjacency matrix. Then, the O(n) solution is to simply read it in and create an adjacency list/matrix upon which you can perform DFS (limited by vertical/horizontal directions), you simply count the number of DFS forests created and that's your answer.
If you want it (assuming that the input is a String; change to 2D would be trivial):
So I'm working on the O(1) space solution now, which
should involve traversing the adjacency matrix using charAt() or something of the sort.is looking like it'll work best if the input is a 2D array (duh). I'm having trouble seeing how you could do this without implementing your own list so that you keep track of visited "spots," but it's also 2:30 so I'm going to get some sleep and see if that helps. This is a good one!EDIT: caught a bug
1
u/[deleted] Dec 19 '15 edited Dec 19 '15
I am on mobile so I am just gonna pseudo code this out, but would something like this work?
1
u/brickmaus Jan 18 '16
best I have so far for the constant space solution is this:
but that fails for
and I'm not really sure how to account for the "lakes"
EDIT: for the normal solution, would one be better off using union-find than DFS?
1
u/tom83 Dec 19 '15
I think this should work.
iterate over the cells.
If a cell is an island AND left neighbour is not an island AND top neighbour is not an island THEN numIslands++
return numIslands
EDIT: this obviously does not work :-(
0
u/sectoidfodder Dec 19 '15
Iterate through and simultaneously count:
(# islands) = (# land tiles) - (# adjacencies) + (# blocks)
2
u/[deleted] Dec 19 '15 edited Dec 19 '15
[removed] — view removed comment