2013-02-21 45 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