Reputation: 53
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).
Upvotes: 5
Views: 3393
Reputation: 1182
Go ahead and make a duplicate graph a[n][n]
with a[i][j] = 1
if i
and j
are connected.
Then you can do the following:
int count = 0;
void dfs(int i)
{
int k;
for(k = 0; k < n; k++)
{
if(A[i][k] == 1 && !visited[k])
{
count++;
visited[k] = 1;
dfs(k);
}
}
}
for(i=0; i < n;i++)
{
if(!visited[i])
{
count=1;
visited[i]=1;
dfs(i);
// map i with count .. here
}
}
So once you have done mapping count of nodes in a network with one of its node .
You'll find value count and if count == total_no_of_1's
If so then network 1 is connected .if not then same with 2's and and declare result .
Upvotes: 0
Reputation: 33545
Maintain a UnionFind data structure from the beginning, each entry representing each cell. Initially, perform a Union on adjacent cells with the same values. When a player marks a cell, perform a union() with the adjacent cells if the value is the same as the player's value. In the Union find, you can keep track of the number of cells that have a value, when that number is equal to the number of times that value was inserted, you have a winner.
You also do it Linearly using the algorithm described here
Upvotes: 0
Reputation: 18594
This question is not so easy. It looks to me you can look at your matrix as a graph and you try to find out if your graph is connected. i.e. is the graph of 1s connected and is the graph of 2s connected. Here you see a few algorithms. Since you are creating the graph you can also keep track of the groups of nodes a player is creating and upon creating a new node, you can check to how many groups is the new node connected and union whatever get connected by the new node (or create a new group containing your new node if it does not connect anything).
btw you can convert any recursion to a loop but this should be necessary only if your stack gets exhausted.
Upvotes: 0
Reputation: 4878
Here are some tips:
boolean
matrix and a counter, to keep track of which ones you've already checked and how many of them.Upvotes: 1