简体   繁体   中英

Implement a recursive function in int main() [c++]

I am using a recursive floodfill function in my program. The program is given below

void floodfill(int x, int y, int &array[100][100])
{
 if (array[x][y]==0)
  {
   array[x][y]=1;
   floodfill(x+1, y, array);
   floodfill(x, y+1, array);
   floodfill(x-1, y, array);
   floodfill(x, y-1, array);
  }
}

int main()
{
   int x= 1;// x and y is the point to start the floodfill
   int y= 10;
   int array[100][100] = {0};

   floodfill(x, y, array); 
}

I was wondering if there is a way to program this recursive function to happen completely inside the int main loop without creating a function?

PS:- I am aware that it is good programming practice to define a function and then use it in the main program, but the architecture of the project I am working on does not enable me to do floodfill using function. hence I want the complete floodfill program in the int main section.Also this is not the complete code. the part where the values of the array get initialized are not provided in the code.

Short answer: No.

You need to pass parameters to make your code work. Main takes no parameters.

And I then feel the need to ask why you would want to do that? It's good programming practice to break your code down to small, well defined parts, that carry out a specific task. And then you isolate that in a function, and you document/describe that function for everyone else to understand what it does.

So even if you could do that, you really should refrain from doing it.

DFS can be implemented without recursion using stack only, so u might want to see this: https://www.codeproject.com/Tips/723337/Depth-First-Search-DFS-Non-recursive

this code is implemented for the tree, but the algorithm is the same.

Local non-static variables, including arrays like your array , are by default not initialized. Their values will be indeterminate and seem almost random.

Using such variables in any way, except to initialize them, leads to undefined behavior .

And that's what happens because you compare a value in your array without it being initialized.

Furthermore, and also a source of undefined behavior , you have no bounds-checking! That means your function can (and will) go out of bounds of your array.


To solve the first problem you need to initialize your array:

int array[100][100] = { 0 };  // Set all elements to zero

To solve the second problem you need to add bounds-checking in your function:

if (x < 0 || x >= 100 || y < 0 || y >= 100)
    return;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM