I have been struggling with an algorithmic problem for a couple of days now, I tried a lot of ways to solve it, but they weren't accurate / fast enough, so I'm counting on you - I'm looking for tips or anything what would be helpful.
So the problem is following, there is square two-dimensional array of bools
bool array[n][n] (n <= 1000)
And as you can presume, it is full of ones and zeros, but ones are always grouped in rectangles, like that:
11100
11100
00001
11100
The algorithm can change two zeros into ones and form as big as possible shape of ones (the formed shape doesn't have to be rectangular) and return the number of ones forming this shape. Diagonal connections are not counted.
for instance:
101
010
101
Should return 7. The problem is that, this algorithm should work as fast as possible, let's say 1-2 seconds for 1000x1000 array is going to be the upper border. So what I have tried:
Firstly, I grouped the squares of ones into groups and formed an array with their sizes and X, Y of corners. Then I was checking the relations between them, but it was very hard to effectively find the group with the biggest potential (especially when the given array was like a chessboard). I was just checking the groups one after another, check its adjacent groups, and then check the next ones for a second additional one to put. It was like brute force, so checking about 500 000 (for a 1000x1000 chessboard) groups was just too much.
Another method I tried was to create an array with its neighbors for every zero, but it was very unoptimal to find another group of ones, again, it was brute force.
I'm sorry for my English if there are any mistakes, I'm not a native speaker. So do you have any tips for me, any links to algorithms or similar problems? Maybe somebody is going to write a (pseudo)code? Anything you can do to help, I will be grateful.