How to Label groups within a 2D array using recursion

百般思念 提交于 2020-12-06 15:49:25

问题


I need to write a a method in my code that can take a two dimensional array and return how many different groups there are within the array. A group is defined as, "all cells connected directly to other cells in the up/down/left/right (not diagonal) directions" where a cell in the array would be represented by an asterisk. I need to write a method that iterates through the entire array that also calls a recursive method that changes every asterisk into a letter that is unique to that group. For example this is a sample input:

char image[][] = {
                {'*','*',' ',' ',' ',' ',' ',' ','*',' '},
                {' ','*',' ',' ',' ',' ',' ',' ','*',' '},
                {' ',' ',' ',' ',' ',' ','*','*',' ',' '},
                {' ','*',' ',' ','*','*','*',' ',' ',' '},
                {' ','*','*',' ','*',' ','*',' ','*',' '},
                {' ','*','*',' ','*','*','*','*','*','*'},
                {' ',' ',' ',' ',' ',' ',' ',' ','*',' '},
                {' ',' ',' ',' ',' ',' ',' ',' ','*',' '},
                {' ',' ',' ','*','*','*',' ',' ','*',' '},
                {' ',' ',' ',' ',' ','*',' ',' ','*',' '}
        };
and the output would be something like this:

aa      b 
 a      b 
      cc  
 d  ccc   
 dd c c c 
 dd cccccc
        c 
        c 
   eee  c 
     e  c 
I mostly need help with the method that iterates through the given image because I don't know how to make the code distinguish between the groups.

回答1:


Your concept should be like this.

checkField (x, y, char)
  x,y is out of bounds; return;

  if current field has asterix do
     current field = char; // Prevents new checks!
     checkField (x+1, y, char); // right field
     checkField (x+-1,y, char); //l left field 
     // top and bottem field.
  else do
    // Advance to next Field; Next field has to be in bounds. At the end of the line you have to go to the next line;
    checkField( .., ..., char++)
end;

The first call would be checkField (0, 0 , 'a');

You need to create a new array of chars. This would be an instance variable.

You could model the x, y matrix as array. Where x mod y is a line. This would make advanceing easier. But less intuitiv.

Try to implement the pseudocode and feel free to update you question in detail.



来源:https://stackoverflow.com/questions/64960511/how-to-label-groups-within-a-2d-array-using-recursion

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!