我得到了一系列非负整数。
43 18 5 67 1 72 16 17 15 93 38 6 83 10 49 98 7 47 61 52 71 79 82 52 8
我需要将其存储在外部输入的 m * n 数组中。如下:
m = 5
n = 5
然后,我需要计算2D数组的某些部分的总和。 (我已经完成了这部分)。
我存储数字的理想方法:
1. Initialize starti,startj = 0.
2. Initialize endi = m , endj = n.
3. Store the remaining numbers in array[starti][j], where j starts from startj and ends at endj.
4. Store the remaining numbers in array[i][endj], where i starts from starti and ends at endi.
5. Store the remaining numbers in array[endi][j], where j starts from endj and ends at startj.
6. Store the remaining numbers in array[i][endj], where i starts from endi and ends at starti.
7. Decrement endi and endj by 1.
8. Increment starti and start j by 1.
9. Repeat the steps 3 - 8 until the last number is stored.
问题:有没有更好的方法来解决这个问题?
其他:我一直尝试使用formula to find where the last element is stored before doing all these operation.
答案 0 :(得分:0)
这是一种方式。
首先,你可以开始递归思考
有一个像`fill(m,n,starting_position,direction)
这样的签名的方法递归版本看起来像
fill(m,n, starting_position, direction) {
// If m=0 or n=0 you have a base case.
// Start at starting position, and fill in the direction.
// Decrement m or n, depending on the direction
// Compute new starting position and direction
// Recursively call fill with the updated m,n, starting_pos, direction
}
现在注意这个方法是尾递归的,所以你可以去除递归并用while循环替换它,while循环的条件来自基本情况。