2013-02-21 145 views
0

在给定的二维正方形(n * n)偶数大小的数组中,我想从起始角到中心遍历。以下是更多信息的图片。二维数组遍历从中心到中心

enter image description here

我的算法是从角落开始和维护两个全局变量作为currentXcurrentY和运行loop直到currentXcurrentY到达市中心。以下是我的伪代码 -

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. 

这是正确的方法吗?有没有更好的方法来以相同的方式遍历它?

回答

1

Psuedocode“使用编程语言的结构约定,但是用于人类阅读而不是机器阅读。” (http://en.wikipedia.org/wiki/Pseudocode) 我建议写符合这个定义的psuedocode会对你有很大的好处,并帮助你考虑如何解决你的问题。

你的算法

似乎表明,你是

  • 检查,如果你在你的目标 “END”,如果你不
    • 向右移动
    • 移动down
    • 左移

这意味着你将永远不会得到任何地方。一个解决方案

我的容器大小N * N 的,因此intially

起点边界是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