A c program to traverse a n*n matrix
We have a n*n matrix for 开发者_运维技巧example we take n=4 and the matrix is given below.
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
We have to traverse it in the sequence:
1, 2, 3, 4, 8, 12, 16, 15, 14, 13, 9, 5, 6, 7, 11, 10
How can I do this?
"Traversing" in this case probably means accessing and printing each entry.You want to go through it in a clockwise spiral, starting from the top.
Here is an English-sentence-style description of what you need to do:
If you can find a way to go to the TOP-LEFT element of a sub-matrix, read off the entries in the top row left-to-right, read off the entries in the right column top-to-bottom, entries in the bottom row right-to-left, and then the left column bottom-to-top, you have one iteration. You can take the remaining sub-matrix and continue until you have nothing left.
Further hints:
From the cell M[x][y],
- M[x][y+1] is the cell to the RIGHT (so long as y+1<n)
- M[x][y-1] is the cell to the LEFT (so long as y>0)
- M[x+1][y] is the cell BELOW (so long as x+1<n)
- M[x-1][y] is the cell ABOVE (so long as x>0)
First of all, try to find an appropriate type to model your matrix, so that it's easy to work with it. At the least, it should be a type which allows you to access elements in the matrix by their row/column number, so that you can basically access the element in row i
and column j
of the matrix m
similiar to m(i, j)
Assuming you found such a type, notice that you're asked to iterate the matrix in a spiral (clock-wise) fashion. So there is a repetition here: each round of the spiral is much the same as the others, except that the inner spirals are a bit smaller; in fact, each spiral is smaller than the previous one by a constant amount.
精彩评论