Implement zigzag algorithm