Finding all adjacent elements in a 2D array

后端 未结 5 1385
半阙折子戏
半阙折子戏 2021-02-15 18:07

I am working on a project where at one point I am stuck.

My question is for example I have the following 2D array containing 3 different integers.

2 2 2          


        
5条回答
  •  不思量自难忘°
    2021-02-15 18:51

    You could treat this like a picture in a paint application. Perform a flood-fill on each element in your 2D array (unless its filled already by something else) and keep track how many pixels you filled in each step.

    If your array is declared like

    int elements[5][5];
    

    Then introduce a second array which tells whether you filled an element already (if you like, use a different type like bool if thats's okay in your C program):

    int pixelFilled[5][5];
    memset( pixelFilled, 0, sizeof( pixelFilled ) );
    

    Next, write a recursive function which performs a flood fill and returns the numbers of elements which were filled (I'm writing this from the top of my head, no guarantee whatsoever that this function works as it is):

    int floodFill( int x, int y ) {
      int filledPixels = 0;
      if ( !pixelFilled[x][y] ) {
        ++filledPixels;
        pixelFilled[x][y] = 1;
      } else {
        return 0;
      }
      if ( x < 4 && elements[x+1][y] == elements[x][y] )
        filledPixels += floodFill( x + 1, y );
      if ( x > 0 && elements[x-1][y] == elements[x][y] )
        filledPixels += floodFill( x - 1, y );
      if ( y < 4  && elements[x][y+1] == elements[x][y] )
        filledPixels += floodFill( x, y + 1 );
      if ( y > 0  && elements[x][y-1] == elements[x][y] )
        filledPixels += floodFill( x, y - 1 );
      return filledPixels;
    }
    

    Finally, iterate over your array and try to fill it completely. Keep track of the largest filled array:

    int thisArea = 0;
    int largestArea = 0;
    int x, y;
    for ( y = 0; y < 5; ++y ) {
      for ( x = 0; x < 5; ++x ) {
        thisArea = floodFill( x, y );
        if (thisArea > largestArea ) {
          largestArea = thisArea;
        }
      }
    }
    

    Now, largestArea should contain the size of the longest chain of adjacent elements.

提交回复
热议问题