Matrix spiral algorithm