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++
Another way is to print top, right, bottom, left of each level (top and bottom are edge to edge) and print the odd innermost layer separately.
(m):
    rows = m.length() -1
    cols = m[0].length() -1
    minDim = min(rows, cols) +1
    layers = minDim /2
    layer = 0
    while layer < layers:
        i = j = layer
        while j <= cols -layer:
            print(i, j)
            j++
        j-- i++
        while i <= rows -layer -1:
            print(i, j)
            i++
        while j >= layer:
            print(i, j)
            j--
        j++ i--
        while i >= layer +1:
            print(i, j)
            i--
        layer++
    // odd innermost layer
    if minDim %2 == 1:
        if max(rows, cols) == rows:
            for i = layers, i <= rows -layers, i++:
                print(i, j)
        else: //cols
            for j = layers, j <= cols -layers, j++:
                print(i, j)
[Hat tip to MA]

No comments:

Post a Comment