I have a 2D list which is a game board containing either an empty space which is a dot (.), an "x" or an "o". I also have a list called groups = [] Each element in this list will be a another list (group), and that list will contain n amount of lists, where each list will look like this: [x, y] (x and y coordinates).
A group is made only of o's or x'es. A group might only be one stone (x or o). A stone belongs to a group if it has one or more connections. A connection is where the stone (x for example) has a same "color" (x - black, o - white) stone next to it (x - 1, x + 1) or above/below it (y - 1, y + 1). Here's a 4x4 board example.
[['x', 'x', '.', 'x'],
['x', '.', '.', '.'],
['.', '.', '.', '.'],
['x', 'x', '.', '.']]
here it would look like this:
groups = [ [ [0, 0], [1, 0], [0, 1] ], [ [0, 3], [1, 3] ], [ [3, 0] ] ]
I've came up with a code, which works but isn't efficient enough. Also, if my explanation of the problem isn't good enough, write a comment and I'll try to explain it further. Here's the code I've came up with:
if len(cells) > 0:
while len(niezuzyte) != 0:
grupa = [niezuzyte[0]]
zuzyte.append(niezuzyte[0])
niezuzyte = [x for x in cells if x not in zuzyte]
for ziomek in grupa:
for cel in cells:
if abs(cel[0] - ziomek[0]) <= 1 and abs(cel[1] - ziomek[1]) <= 1:
if abs(cel[0] - ziomek[0]) + abs(cel[1] - ziomek[1]) < 2 and cel not in grupa:
zuzyte.append(cel)
grupa.append(cel)
do_wyjeby.append(grupa)
niezuzyte = [x for x in cells if x not in zuzyte]
the list names are polish but I hope it doesn't matter too much, cells is a group with indexes of all either x'es or o's on the board. The code also gives me groups of [y, x] instead of [x, y] but that shouldn't matter too much. Any tips/help would be greatly appreaciated, thanks!