在给定的2D square(n * n)偶数大小数组中,我想从起始角到其中心遍历。以下是更多信息的图片。
我的算法是从角落开始并维护两个全局变量currentX
和currentY
并运行loop
直到currentX
和currentY
到达中央。下面是我的伪代码 -
x=0
y=0
currentX=0
currentY=0
while(currentX != centerX and currentY != centerY){
currentX=travel_in_x_plus_direction(x,n);
currenty=travel_in_y_plus_direction(y,n);
currentX=travel_in_x_minux_direction(currentX,x);
currentY=travel_in_y_minux_direction(currentY,y-1);
n--;
x--;
y--;
}
The function travel_in_x_plus_direction(currentX) traverse the array starting from currentX till x and returns the final value of x. The same concept applies for rest of the functions also.
这是正确的方法吗?有没有更好的方法以同样的方式遍历它?
答案 0 :(得分:1)
Psuedocode “使用编程语言的结构约定,但是用于人类阅读而不是机器阅读。” (http://en.wikipedia.org/wiki/Pseudocode) 我建议编写符合此定义的伪代码对您有很大帮助,并帮助您思考如何解决问题。
您的算法
似乎暗示你是
这意味着你永远无法到达任何地方。
解决方案的起点
我的容器大小为n * n 因此,边界最初为n * n 如果我穿过一个单独的广场,它就会成为边界的一部分。
路径非常简单,首先向右移动,然后每当阻挡改变方向时。方向序列按顺序向右,向下,向左,向上,直到达到目标。
HorizontalMax = n (the right wall)
HorizontalMin = 0 (the left wall)
VerticalMax = n (the bottom wall)
VerticalMin = 0 (the top wall)
While not at goal
While not at right boundary or goal
Move right
Increment VerticalMin (you just moved along the top wall)
While not at bottom boundary or goal
Move down
Decrement HorizontalMax (you just moved along the right wall)
While not at left boundary or goal
Move left
Decrement VerticalMax (you just moved along the bottom wall)
While not at top boundary or goal
Move up
Increment HorizontalMin (you just moved along the left wall)
End