Un algoritmo tipo "floodfill" adattato in qualche maniera potrebbe fare al caso tuo.