ravi
ravi

Reputation: 6336

2D Array traversal from corner to center

In a given 2D square (n*n) even size array, i want to traverse from a starting corner till its center. Below is the image for more info.

enter image description here

My algorithm is to start from corner and maintain two global variable as currentX and currentY and run a loop until currentX and currentY reach to the center. Below is my pseudo code-

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.

Is this the right way? Is there any better way to traverse it in the same manner?

Upvotes: 0

Views: 632

Answers (1)

Aligma
Aligma

Reputation: 572

Psuedocode "uses the structural conventions of a programming language, but is intended for human reading rather than machine reading." (http://en.wikipedia.org/wiki/Pseudocode) I would suggest that writing psuedocode that conforms to this definition would be of great benefit to you and help you think about how you are going about solving your problem.

Your algorithm

Seems to suggest that you are

  • checking if you are at your goal "END", and if you are not
    • Move right
    • Move down
    • Move left
    • Move up

which means you will never get anywhere.

Starting point for a solution

My container is of size n*n therefore intially the boundary is n*n if I travel through an individual square, it becomes part of the boundary.

The path is quite simple, begin by moving right, and then whenever blocked change direction. The sequence of directions is right, down, left, up in that order, until the goal is reached.

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

Upvotes: 1

Related Questions