-1

While trying to create a N by N spiral matrix for number 1 to square(N) , using the usual algorithm for spiral matrix , there is an unexpected output in one of the rows which cannot be found even on rechecking.

def getSpiralOrder(N):
  matrix = [ [ 0 for i in range(N) ] for j in range(N) ]
  c = 1
  rS = 0
  rE = len(matrix) 
  cS = 0
  cE = len(matrix[0]) 
  while(rS < rE and cS < cE):
   for i in range(cS , cE ):
     matrix[rS][i]=c
     c = c + 1
   rS += 1

   for i in range(rS , rE):
     matrix[i][cE - 1]=c
     c = c + 1 
   cE -= 1  
   for i in range(cS , cE):
     matrix[rE - 1][cE - i - 1]=c
     c =c + 1
   rE -= 1  
   for i in range(rS,rE):
     matrix[rE - i ][cS]=c
     c = c + 1
   cS += 1  
  
  return(matrix)

n = int(input())
print(getSpiralOrder(n))

Output should be: [[1, 2, 3, 4], [12, 13, 14, 5], [11, 16 , 15, 6], [10, 9, 8, 7]]

But output coming is: [[1, 2, 3, 4], [12, 13, 14, 5], [16, 0, 15, 6], [10, 9, 8, 7]]

Turns out all rows are correct except the third one.

  • 2
    Does this answer your question? [How to step through Python code to help debug issues?](https://stackoverflow.com/questions/4929251/how-to-step-through-python-code-to-help-debug-issues) – mkrieger1 May 12 '22 at 14:43
  • 1
    Please use 4-space indentation to make the code structure easier to see. – Barmar May 12 '22 at 14:58

1 Answers1

1

Your last two for loops are wrong:

def getSpiralOrder(N):
    matrix = [ [ 0 for i in range(N) ] for j in range(N) ]
    c = 1
    rS = 0
    rE = len(matrix) 
    cS = 0
    cE = len(matrix[0]) 
    while(rS < rE and cS < cE):
        for i in range(cS , cE ):
            matrix[rS][i]=c
            c = c + 1
        rS += 1

        for i in range(rS , rE):
            matrix[i][cE - 1]=c
            c = c + 1 
        cE -= 1  
        # should go from cE - 1 not cE - cS - 1
        for i in range(cE-cS):
            matrix[rE - 1][cE - i - 1]=c
            c =c + 1
        rE -= 1  
        # similar here
        for i in range(rE-rS):
            matrix[rE - i -1][cS]=c
            c = c + 1
        cS += 1  
    return(matrix)
Z Li
  • 4,133
  • 1
  • 4
  • 19
  • Thanks , it works now, but how is range(cE-cS) different from range(cS , cE) ? I thought they are the same. – pranjal verma May 12 '22 at 16:15
  • 1
    they iterate the same number of times, but the first one starts from 0 while the latter starts from `cS` – Z Li May 12 '22 at 16:33