- A+

I want to stop the recursive function when it reaches 3000 depth. how do I do it?

` void DFS(bool M[][COL], int row, int col) { short k; M[row][col] = 0; for (k = 0; k < 4; k++){ if(k==0){ if (isSafe(M, row , col - 1) ){ DFS(M, row , col - 1); } } if(k==1){ if (isSafe(M, row , col + 1) ){ DFS(M, row , col + 1); } } if(k==2){ if (isSafe(M, row + 1, col) ){ DFS(M, row + 1, col); } } if(k==3){ if (isSafe(M, row - 1 , col) ){ DFS(M, row - 1, col); } } } } `

When I added the counter, I tried to return it when it was 3000, but I can't say I was very successful.

I have 512 * 512 matrix and I am looking for an island in this matrix. The recursive function gives the error if one of the island's area is more than 10000 units.

I want to stop the recursive function when it reaches 3000 depth

A general solution to this is to add a "depth" argument to the function, and pass `depth + 1`

to each recursive call (or `remaining_depth - 1`

if you want to count backwards). To hide this from an outward-facing API, make the public function – without the depth argument – simply call the actual function with the initial value for `depth`

.

For example:

`#define MAX_DEPTH 3000 static void dfs_(bool M[][COL], int row, int col, int depth) { if (!isSafe(M, row, col)) { return; } M[row][col] = 0; if (depth >= MAX_DEPTH) { return; } dfs_(M, row, col - 1, depth + 1); dfs_(M, row, col + 1, depth + 1); dfs_(M, row - 1, col, depth + 1); dfs_(M, row + 1, col, depth + 1); } void DFS(bool M[][COL], int row, int col) { dfs_(M, row, col, 1); } `