问题
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[][] = {
{'*','*',' ',' ',' ',' ',' ',' ','*',' '},
{' ','*',' ',' ',' ',' ',' ',' ','*',' '},
{' ',' ',' ',' ',' ',' ','*','*',' ',' '},
{' ','*',' ',' ','*','*','*',' ',' ',' '},
{' ','*','*',' ','*',' ','*',' ','*',' '},
{' ','*','*',' ','*','*','*','*','*','*'},
{' ',' ',' ',' ',' ',' ',' ',' ','*',' '},
{' ',' ',' ',' ',' ',' ',' ',' ','*',' '},
{' ',' ',' ','*','*','*',' ',' ','*',' '},
{' ',' ',' ',' ',' ','*',' ',' ','*',' '}
};
aa b
a b
cc
d ccc
dd c c c
dd cccccc
c
c
eee c
e c
回答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