Problem
So imagine you are given a m * n matrix like this:
Grid = 4 * 4
1 1 1 1
2 2 2 2
3 3 3 3
4 4 4 4
You want to connect from the top left corner to the bottom right corner and you can only go right or down. In addition, you want to find the operations needed to get the desired sum.
For example:
Script found in Text Book, not clear
def move(m, n, sum):
count = m + n - 1
max_val = m
s = sum
r = []
while max_val > 0:
if count <= 0:
return False, r
least = max_val * ((max_val - 1) / 2)
r.append(max_val)
s -= max_val
count -= 1
while ((count > 0) and (s > least + (count - (max_val - 1)) * (max_val - 1))):
r.append(max_val)
s -= max_val
count -= 1
if s < least:
return False, r
max_val -= 1
return True, r
def combine(m, n, sum):
result, new_res = move(m, n, sum)
new_res.reverse()
for i in range(1, len(new_res)):
if new_res[i] == new_res[i - 1]:
print("R")
else:
print("D")
combine(4, 4, 16)
I don't quite understand the solution.
Can someone explain the Algorithm?
Especially in the function move where it does this check in the while loop:
while ((count > 0) and (s > least + (count - (max_val - 1)) * (max_val - 1))):
Questions
- What is the name of this algorithm?
- How does this Script Work?
- What's the run time (Time complexity)?
Thank you!