2013-02-21 2 views
0

주어진 2D 사각형 (n * n) 짝수 크기의 배열에서 시작점에서 중심까지 횡단하길 원합니다. 아래는 더 많은 정보를위한 이미지입니다.모서리에서 2D 배열 탐색

enter image description here

내 알고리즘은 코너에서 시작 currentXcurrentY 같은 두 개의 전역 변수를 유지하고 센터 currentXcurrentY에 도달 할 때까지 loop를 실행하는 것입니다. 아래는 내 의사 코드입니다.

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"에있는 경우

  • 검사 것을 제안하는 것, 그리고 당신은 바로
  • 이동
    • 이동하지 않은 경우 아래로
    • 왼쪽으로 이동
    • 어디서든 얻을하지 않습니다 의미까지

이동합니다. 나는 개인 평방를 통해 여행하는 경우

내 컨테이너 따라서 intially 크기 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