Skip to content

Instantly share code, notes, and snippets.

@jianminchen
Created January 22, 2018 21:18
Show Gist options
  • Save jianminchen/26e6ce3a74aa58eeeead52c894645276 to your computer and use it in GitHub Desktop.
Save jianminchen/26e6ce3a74aa58eeeead52c894645276 to your computer and use it in GitHub Desktop.
Union find - number of islands II - study code - source code is based on Java code https://discuss.leetcode.com/topic/29613/easiest-java-solution-with-explanations
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NumberOfIslandII
{
class Program
{
/// <summary>
/// will come back to add test case, and the make the code as a template
/// as other union-find algorithm
/// 1/22/2018
/// </summary>
/// <param name="args"></param>
static void Main(string[] args)
{
}
int[][] fourNeighbors = new int[][] {
new int[] { 0, 1 },
new int[] { 1, 0 },
new int[] { -1, 0 },
new int[] { 0, -1 }
};
/// <summary>
/// apply union-find algorithm
/// code review will be added later. 1/22/2018
/// </summary>
/// <param name="m"></param>
/// <param name="n"></param>
/// <param name="positions"></param>
/// <returns></returns>
public List<int> numIslands2(int m, int n, int[][] positions) {
var result = new List<int>();
if(m <= 0 || n <= 0)
{
return result;
}
int count = 0; // number of islands
var roots = new int[m * n]; // one island = one tree
roots.Select( value => value = -1 ).ToArray<int>();;
foreach(var node in positions) {
int root = n * node[0] + node[1]; // assume new point is isolated island
roots[root] = root; // add new island
count++;
foreach(var neighbor in fourNeighbors) {
int x = node[0] + neighbor[0];
int y = node[1] + neighbor[1];
int uniqueId = n * x + y;
if(x < 0 || x >= m || y < 0 || y >= n || roots[uniqueId] == -1) continue;
int rootNb = findIsland(roots, uniqueId);
if(root != rootNb) { // if neighbor is in another island
roots[root] = rootNb; // union two islands
root = rootNb; // current tree root = joined tree root
count--;
}
}
result.Add(count);
}
return result;
}
/// <summary>
/// path compression is implemented
/// code review by Julia on 1/22/2018
/// </summary>
/// <param name="roots"></param>
/// <param name="id"></param>
/// <returns></returns>
public int findIsland(int[] roots, int id)
{
while (id != roots[id])
{
roots[id] = roots[roots[id]]; // only one line added, it is for path compression
id = roots[id];
}
return id;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment