Spiral Matrix

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • niharikamd
    New Member
    • Apr 2010
    • 1

    Spiral Matrix

    hi
    i want a java source code for spiral matix
    if we give a input matrix as
    1 2 3
    4 5 6
    7 8 9
    so the output matrix should be
    2 3 4
    5 6 7
    8 9 1

    Or

    9 1 2
    3 4 5
    6 7 8
    i hope you will help for this.....
  • jkmyoung
    Recognized Expert Top Contributor
    • Mar 2006
    • 2057

    #2
    One possible method:
    Think of the indices:
    0 -> [0][0]
    1 -> [0][1]
    2 -> [0][2]
    3 -> [1][0]
    4 -> [1][1]
    5 -> [1][2]
    6 -> [2][0]
    7 -> [2][1]
    8 -> [2][2]

    Formula for i -> x, y
    x = i / 3;
    y = i % 3;

    To shift one position, add or subtract one from i, and do the same conversion (with minor modification) to x and y.

    Comment

    Working...