Finding all adjacent elements in a 2D array

后端 未结 5 1389
半阙折子戏
半阙折子戏 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:57

    1. define another 2d array of the same size, initialize all cells to 0
    2. set maxval to 0
    3. if helper array is full of 1's go to 5, otherwise find a cell with 0 and do:
      3.1 change value of the cell to 1
      3.2 set a counter to 1
      3.3 check all adjacent cells, if they're 0 in the helper array and the same value as current cell in the input array then counter++ and go to 2.1 with new coordinates.
    4. maxval = max(maxval,counter), go to 3
    5. return maxval

    steps 3.1-3.3 should be implemented as a recursive function which takes coordinate and both arrays as arguments and returns 1+the sum of the returned values from the recursive calls.

提交回复
热议问题