Thursday, August 11, 2016

print matrix in spiral manner

m:
 12345
layers = 1

m:
 12345
 67890
layers = 1

m:
 1234
 5678
 9012
layers = 2

m:
 1234
 5678
 9012
 3456
layers = 2

min(rows/cols) layers
            1      1 
            2      1
            3      2
            4      2

i.e. layers = (min(rows, cols) +1) /2
For each layer in layers, four while loops starting from location [layer, layer] print out each side of spiral (right, down, left, up). Break out if a while loop body is not executed.
(m):
    rows = m.length()
    cols = m[0].length()
    layers = (min(rows, cols) +1) /2
    while layer < layers:
        i = j = layer
        if !(i < rows -layer):
            break
        while i < rows -layer:
            print(i,j)
            i++
        i-- j++
        if !(j < cols -layer):
            break
        while j < cols -layer:
            print(i,j)
            j++
        j-- i--
        if !(i >= layer):
            break
        while i >= layer:
            print(i,j)
            i--
        i++ j--
        if !(j >= layer):
            break
        while j >= layer:
            if i == j == layer:
                break
            print(i,j)
            j--
        layer++
[Hat tip to MA]

No comments:

Post a Comment