How to write a recursive function for counting the amount of ways you can step through an array?

Hello, I'm trying to write a function that determines how many valid paths a walker can get through an array given the rule that the walker can only move up in the 2D array or to the right, never to the left or down.

The walker always starts at the bottom left of an array no matter the size and is trying to get to the top right. I'm trying to write a recursive function that counts how many different valid paths a walker can get to the top right.
Last edited on
Each step along the way you're asking yourself, "How many ways are there to get to the end, if I'm only allowed to go up or right?" The answer is, "The number of ways to get to the end is the sum of:
1. the number of ways to get to the end if I go up
2. the number of ways to get to the end if I go right"

That's where the recursion comes in. To find out the number of paths from your current spot, you gotta find the answer to the number of paths for each direction you're allowed to go.
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
#include <iostream>

//let's say rows and columns are numbered starting from 1 to total
int countWaysToEnd(int currentRow, int currentCol, int totalRow, int totalCol)
{
    //base case
    if(currentRow == totalRow && currentCol == totalCol)
    {
        return 1;
    }

    int waysToEndIfIGoUp = 0;
    if(currentRow < totalRow) //if I can move up
    {
        //currentRow + 1 is what row we're on if we move up
        waysToEndIfIGoUp = countWaysToEnd(currentRow + 1, currentCol, totalRow, totalCol);
    }

    int waysToEndIfIGoRight = 0;
    if(currentCol < totalCol) //if I can move right
    {
        //currentCol + 1 is what row we're on if we move right
        waysToEndIfIGoRight = countWaysToEnd(currentRow, currentCol + 1, totalRow, totalCol);
    }

    return waysToEndIfIGoRight + waysToEndIfIGoUp;
}

int main()
{
    int startingRow = 1;
    int startingCol = 1;
    int totalRows = 3;
    int totalCols = 4;
    std::cout << countWaysToEnd(startingRow, startingCol, totalRows, totalCols) << std::endl;  //should get 10
    return 0;
}

EDIT: Mixed up my up and rights with my rows and columns
Last edited on
@booradley60 Thank you, great answer. Helped me understand it better. Very much appreciated, thank you!
Topic archived. No new replies allowed.