Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unique paths algorithm and tests added to dynamic programming section #1438

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions algorithms/dp/unique_paths.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
"""

Context: we have an m*n grid (m,n are integers) and we are looking to find the amount of unique paths
we can take in order to go from the top left square to the bottom right one. We can only move one cell down
or one cell to the right each time.

"""


def unique_paths(m, n):
# the dynamic programming matrix we are going to use in order to get the final solution
# we initialize an m*n matrix of zeros
dp = [[0 for _ in range(n)] for __ in range(m)]

# dp[i][j] = the amount of unique paths we can take in order to reach the square of the grid
# which has coordinates i and j.

for i in range(m):
dp[i][0] = 1
for j in range(n):
dp[0][j] = 1

# Base case: each square in the first row and column has only 1 possible path to them

for i in range(1, m):
for j in range(1, n):
dp[i][j] = dp[i-1][j] + dp[i][j-1]

# for each square, the amount of ways to reach it is equal to the sum of:
# the amount of paths we can take to the square directly above it
# the amount of paths we can take to the square directly to its left

return dp[m-1][n-1]
16 changes: 14 additions & 2 deletions tests/test_dp.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@
longest_increasing_subsequence,
longest_increasing_subsequence_optimized,
longest_increasing_subsequence_optimized2,
int_divide,find_k_factor,
planting_trees, regex_matching
int_divide, find_k_factor,
planting_trees, regex_matching, unique_paths
)


Expand Down Expand Up @@ -259,5 +259,17 @@ def test_symbol_2(self):
self.assertTrue(regex_matching.is_match(s, p))


class TestUniquePaths(unittest.TestCase):
def test2d(self):
m = 3
n = 7
self.assertEqual(unique_paths.unique_paths(m, n), 28)

def test1d(self):
m = 5
self.assertEqual(unique_paths.unique_paths(m, 1), 1)
self.assertEqual(unique_paths.unique_paths(1, m), 1)


if __name__ == '__main__':
unittest.main()