File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes zigzag traverse a matrix Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "zigzag traverse a matrix" Watch "zigzag traverse a matrix" New topic

zigzag traverse a matrix

Sanjeev Mehta

Joined: Feb 13, 2009
Posts: 20
I want to traverse a matrix in zig-zag fashion.

Say my matrix is

a11 a12 a13 a14
a21 a22 a23 a24
a31 a32 a33 a34
a41 a42 a43 a44

I want my output to be

a11 a12 a21 a31 a22 a13 a14 a23 a32 a41 a42 a33 a24 a34 a43 a44.

I have tried doing it using nested if's and else's and it works but the code is messy. I want to know what a clean approach to achieve this should be.

Rob Spoor

Joined: Oct 27, 2005
Posts: 20274

Let's look at the algorithm:
1) start at 1,1 (x == 1, y == 1)
2) move right once (x++)
3) move to the bottom left (x--, y++) until you've reached the left or bottom side
4) move to the bottom (y++)
5) move to the top right (x++, y--) until you've reached the right or top side
6) go to step 2 until you've reached the last cell

A simple loop would now do the trick. Keep in mind that Java arrays start at 0, not 1, so my values for x and y in step 1 are wrong.

How To Ask Questions How To Answer Questions
Sanjeev Mehta

Joined: Feb 13, 2009
Posts: 20
Thanks Rob. But wouldn't there be two loops involved? Because for the lower triangular matrix the traverse order would be :

1. move right once
2. move to the top right
3. move down once
4. move to the bottom left.
Sanjeev Mehta

Joined: Feb 13, 2009
Posts: 20
This is how I implement this atm for an 8x8 matrix

I agree. Here's the link:
subject: zigzag traverse a matrix
It's not a secret anymore!