07 October 2010

Print a Matrix in diagonal zig zag order

Problem:
Given a square matrix, write a program to print the items in zig zag diagonal order.

Following is an example,

So the output expected for the above example is,

1 -> 2 -> 6 -> 3 -> 7 -> 11 -> 4 -> 8 -> 12 -> 16 -> 5 -> 9 -> 13 -> 17 -> 21 -> 10 -> 14 -> 18 -> 22 -> 15 -> 19 -> 23 -> 20 -> 24 -> 25

Solution:

This program is a bit tricky and is very hard to solve immediately when asked in an interview. People who try to attack problems involving matrices always think they need at least two loops to arrive at the solution. But the surprise here is the problem can be solved in just a single loop with a very simple logic. I have provided the solution in C++ below, you may also try to solve the same in the language of your choice!!


Cheers!!
Jack

6 comments:

Unknown said...

well You write the program very intelligently but u didn't write it for general 2d matrix e.g your program doesn't work when matrix is not the square matrix e.g. what happens when M!=N which is not d square matrix

BragBoy said...

@shashank Mani: Dude.. Read the problem statement again. It clearly says SQUARE matrix

KK123 said...
This comment has been removed by the author.
Rahul Tiwari said...

plz edit the code for the case -
row != col .....

vinny said...

i am communion with b....shashank u should read the problem again.

arpit tak said...

yah its works.. nice wrk man.
can u also tell how to print a spiral matrix of same square.