面试29题:

题目:顺时针打印矩阵(同LeetCode 螺旋矩阵打印)

题:输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下矩阵: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 则依次打印出数字1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10.

解题方法一:详见剑指offer

解题代码:

# -*- coding:utf-8 -*-
class Solution:
# matrix类型为二维列表,需要返回列表
def printMatrix(self, matrix):
# write code here
if not matrix or len(matrix)<=0 or len(matrix[0])<=0:
return
start=0
rows=len(matrix)
columns=len(matrix[0])
res=[]
while(columns>start*2 and rows>start*2):
self.printMatrixInCircle(matrix,columns,rows,start,res)
start += 1 return res def printMatrixInCircle(self,matrix,columns,rows,start,res):
endX=columns-1-start
endY=rows-1-start # 从左到右打印一行
for i in range(start,endX+1):
res.append(matrix[start][i]) # 从上到下打印一列
if start<endY:
for i in range(start+1,endY+1):
res.append(matrix[i][endX]) # 从右到左打印一行
if start<endX and start<endY:
for i in range(endX-1,start-1,-1):
res.append(matrix[endY][i]) # 从下到上打印一列
if start<endX and start<endY-1:
for i in range(endY-1,start,-1):
res.append(matrix[i][start])

解题方法二:Python黑魔法:详细思路见 另一篇文章:【算法题9 螺旋矩阵问题】

# -*- coding:utf-8 -*-
class Solution:
# matrix类型为二维列表,需要返回列表
def printMatrix(self, matrix):
# write code here
return matrix and list(matrix.pop(0))+self.printMatrix(zip(*matrix)[::-1])

最新文章

  1. -&gt;code vs 1474 十进制转m进制
  2. Python爬虫Scrapy框架入门(1)
  3. 初学js/jquery 心得
  4. Raspberry Pi 3 FAQ --- connect automatically to &#39;mirrors.zju.edu.cn&#39; when downloading and how to accelerate download
  5. Newtonsoft.Json(Json.net)的基本用法
  6. adb shell 命令详解(转)
  7. 微信消息处理JAXP-sax解析
  8. HDU5418.Victor and World(状压DP)
  9. 通过定时监听input框来实现onkeyup事件-
  10. BZOJ2288: 【POJ Challenge】生日礼物
  11. migrate from weblogic to tomcat: directory mapping--reference
  12. JavaScript 原型链的一点想法
  13. css Block formatting context BFC
  14. 链接分析算法之:主题敏感PageRank
  15. [ 搭建Redis本地服务器实践系列三 ] :图解Redis客户端工具连接Redis服务器
  16. asp.net core 系列之用户认证(authentication)
  17. fdisk命令
  18. [CNN] Tool - Deep Visualization
  19. python 类方法中参数使用默认值的方法
  20. Linux下设置Apache支持Https服务

热门文章

  1. Python内置函数之len()
  2. java-MapDemo
  3. JDBC mysql 中文乱码
  4. java算法学习
  5. IDEA15入门常用设置
  6. Mysql中查看每个IP的连接数
  7. libsvm easy.py ValueError: need more than 0 values to unpack windows下终极解决
  8. Atitit.软件仪表盘(4)--db数据库子系统-监測
  9. Swift学习笔记(一):No such module &#39;Cocoa&#39;
  10. [MongoDB]学习笔记--Linux 安装和运行MongoDB