`

也来一例内螺旋数组python实现

 
阅读更多

 熟悉python,也整一个类似java实现的,功能基本一样,练练手,酷

也可以参考另外一篇java的实现文章,

内螺旋数组java实现

源码如下:

 

#-*-coding:UTF-8-*-
#!/usr/bin/python
##array define
##dennis zhao 27202787@qq.com
##2013-08-02
 
import time,sys

result = [[] for i in range(5)]
initial = [[] for i in range(5)]
directions = [[] for i in range(5)]
print ("="*60);

for k in range(0,5):
    for j in range(1,6):
        result[k].append(0);

for k in range(0,5):
    for j in range(1,6):
        initial[k].append(0);

for k in range(0,5):
    for j in range(1,6):
        directions[k].append('-');


def showData(ll,dirs):
    ret="";
    for i in range(len(ll)):
        s=str(ll[i]);
        ret=ret + s.zfill(2)+ dirs[i] +"\t";
    return ret;

#print ("result",result)
#print ("initial",initial)
#print ("directions",directions)   
count=0
row = 0;
col = -1;

while (count < 5*5):
    #left to right
    col +=1;
    while(col<5 and initial[row][col] == 0):
        initial[row][col]=1;
        count+=1;
        result[row][col] = count;
        directions[row][col] = "→";
        col+=1;
    #print ("first", result);
    #time.sleep(1);
    col-=1;#last column minus 1

    row+=1;#top to down
    while (row < 5 and initial[row][col] == 0):
        initial[row][col] = 1;
        #global count;
        count+=1;
        result[row][col] = count;
        directions[row][col] = "↓";
        row+=1;
    row-=1;#last row minus 1
    #print ("second", count);
    #time.sleep(1);
    col-=1;#right to left
    
    while (col >= 0 and initial[row][col] == 0):
        initial[row][col] = 1;

        count+=1;
        result[row][col] = count;
        directions[row][col] = "←";
        col-=1;
    col+=1;# last column add 1
    #print ("third", count);
    #time.sleep(1);

    # down to top
    row-=1;
    while (row >= 0 and initial[row][col] == 0) :
        initial[row][col] = 1;
        count+=1;
        result[row][col] = count;
        directions[row][col] = "↑";
        row-=1;
    row+=1;# last row add 1
    #print ("fourth", count);
    #time.sleep(1);




for index in range(len(result)):
   print ('Line value (',index+1,'):\t', showData(result[index],directions[index]))


#print ("result",result)
#print ("initial",initial)
#print ("directions",directions)  
print ("="*60);

 

 效果图:



 

  • 大小: 24.6 KB
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics