Using ArrayList<int>

works :slight_smile:

finished code:

//dynamic selection
ArrayList<Integer> selection = new ArrayList<Integer>();
int w = 20, h = 20, clrs = 2;
float scl;
int grid[][] = new int[w][h];

void setup() {
  size(600,600);
  scl = width/w;
  for(int i = 0; i < w; i++) {
    for(int j = 0; j < h; j++) {
      grid[i][j] = floor(random(clrs));
    }
  }
  colorMode(HSB);
}

void draw() {
  background(0);
  for(int i = 0; i < w; i++) {
    for(int j = 0; j < h; j++) {
      fill(map(grid[i][j],0,clrs,0,255),255,255);
      rect(i*scl,j*scl,scl,scl);
      fill(255);
      if(selection.contains(i+j*w)) {
        rect((i+0.25)*scl, (j+0.25)*scl,scl/2,scl/2); 
      }
    }
  }
  //println(selection);
}

void mousePressed() {
  selection.clear();
  beginSelection( floor(map(mouseX,0,width,0,w)), floor(map(mouseY,0,height,0,h)));
}

void beginSelection(int x, int y) {
  selection.add(x+y*w);
  while(doStuff() > 0);
  println(selection);
}

int doStuff() {
  int selected = 0;
  for(int i = 0; i < selection.size(); i++) {
    int gx = selection.get(i) % w, gy = floor((selection.get(i) - gx)/w);
    if(gx > 0) {
      if(grid[gx][gy] == grid[gx-1][gy] && !selection.contains( (gx-1)+gy*w) ) {
        selection.add((gx-1)+gy*w);
        selected++;
      }
    }
    if(gx < w-1) {
      if(grid[gx][gy] == grid[gx+1][gy] && !selection.contains( (gx+1)+gy*w) ) {
        selection.add((gx+1)+gy*w);
        selected++;
      }
    }
    if(gy > 0) {
      if(grid[gx][gy] == grid[gx][gy-1] && !selection.contains( (gx)+(gy-1)*w)) {
        selection.add((gx)+(gy-1)*w);
        selected++;
      }
    } 
    if(gy < h-1) {
      if(grid[gx][gy] == grid[gx][gy+1] && !selection.contains( (gx)+(gy+1)*w)) {
        selection.add((gx)+(gy+1)*w);
        selected++;
      }
    }
  }
  
  return(selected);
}