Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

connected neighbours in a java 2d array

I'm designing an engine for a game which has a 2D array like this:

0,1,1,2,0
0,1,2,1,1
1,0,1,0,2
2,1,2,0,0
2,0,1,0,0

I'm stuck at the "game over" condition as it has to check if the 1's or 2's are connected. It should declare the player with 1's as winner and return this:

 1 1
 1   1 1
1  1
1
  1
    1

I've tried using recursion by checking every position in the array and checking its neighbors in all 8 directions but the method took 45 seconds to run which is inefficient.

Does anyone have any ideas? A pseudo-code example would be appreciated (I'm a slow learner).

like image 547
Mina Saleh Avatar asked Oct 22 '22 12:10

Mina Saleh


1 Answers

What you need is that:

Connected_component_labeling

This gives a pseudo code,

hope it helps

like image 155
smttsp Avatar answered Oct 24 '22 04:10

smttsp