You can do this with a DP-based method. Loop through columns one by one, at each stage keeping track of the groups of connected squares of each colour.

An example, where we can label whites with numbers and blacks with letters:

The first column corresponds to state (0,0,0,A,1). When we add on the next column, we reach state (0,A,0,B,1) - the first and third columns are already joined on the left.

Thus for each possible state, loop through all 2^5 options for the next column, work out what state you get when you combine them, make sure we don't 'cut off' any groups and by the time you reach the end you're done. There aren't that many possible states to work with assuming we label them in increasing order from top to bottom.

If that makes sense.

(Will easily work for 7x7 too).