Recursion

Have anyone knows how to create recursion function? I need to find the biggest ship and returns it's coordinate, ship can be both horizontal and vertical(like a snake) and ships can't touch.It's kinda hard to do it with 2d array and I don't know ho to apply to char array elements.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
  using namespace std;

  char data[MAX][MAX] = {
    {'0', '0', '0', '0', '+', '+', '+', '+', '+', '+'},
    {'+', '0', '0', '0', '+', '0', '0', '0', '0', '+'},
    {'+', '0', '0', '0', '+', '0', '+', '+', '+', '+'},
    {'+', '+', '+', '+', '+', '0', '0', '0', '0','0'},
    {'0', '0', '0', '0', '0', '0', '0', '0', '0', '0'},
    {'0', '0', '0', '0', '0', '0', '0', '0', '0', '0'},
    {'0', '0','0', '0', '0', '0', '0', '0', '0', '0'},
    {'0', '+', '+', '+','+','+','+', '0', '0', '0'},
    {'0', '+', '0', '0','0', '0', '0', '0', '0', '0'},
    {'0', '+', '0', '0','0', '0', '0', '0', '0', '0'},
};





void printArr(char a[MAX][MAX]){

    for (int i = 0; i < MAX; ++i) {
        cout << endl;
        for (int j = 0; j < MAX; ++j) {
            cout << a[i][j] << " ";
        }
    }
}

}
int main(){
 char data[MAX][MAX]= {
    {'0', '0', '0', '0', '+', '+', '+', '+', '+', '+'},
    {'+', '0', '0', '0', '+', '0', '0', '0', '0', '+'},
    {'+', '0', '0', '0', '+', '0', '+', '+', '+', '+'},
    {'+', '+', '+', '+', '+', '0', '0', '0', '0','0'},
    {'0', '0', '0', '0', '0', '0', '0', '0', '0', '0'},
    {'0', '0', '0', '0', '0', '0', '0', '0', '0', '0'},
    {'0', '0','0', '0', '0', '0', '0', '0', '0', '0'},
    {'0', '+', '+', '+','+','+','+', '0', '0', '0'},
    {'0', '+', '0', '0','0', '0', '0', '0', '0', '0'},
    {'0', '+', '0', '0','0', '0', '0', '0', '0', '0'},
};

    printArr(data);

    return 0;
}
A recursion call will look like this
1
2
3
4
5
function()
{
   if(condintion) return;
   else return function();
}


Though your task, if I understood correctly, would fare better with 2d array iteration. Recursive functions cause overhead and stack overflow in C-like languages (C, C++, Java).
Yes, iteration is better than recursion here. Use 2 nested range-based for loops. The outer one iterates through the outer array and the inner one iterates through the inner array.

1
2
3
4
5
6
7
8
9
for (auto &row : array)
{
    for (auto &col : row)
    {
        // Here you have access to the individual elements

        // Do stuff...
    }
}
Last edited on
Thanks for the help
Topic archived. No new replies allowed.