顺时针打印二维矩阵

 

 

 

复制代码

public ArrayList printMatrix(int[][] matrix) {
ArrayList result = new ArrayList();
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
return result;
}
int left = 0;
int right = matrix[0].length - 1;
int top = 0;
int bottom = matrix.length - 1;
while (true) {
//上边界
for (int col = left; col <= right; col++) {
result.add(matrix[top][col]);
}
top++;
if (top > bottom) break;

//右边界
for (int row = top; row <= bottom; row++) {
result.add(matrix[row][right]);
}
right--;
if (left > right) break;

//下边界
for (int col = right; col >= left; col--) {
result.add(matrix[bottom][col]);
}
bottom--;
if (top > bottom) break;

//左边界
for (int row = bottom; row >= top; row--) {
result.add(matrix[row][left]);
}
left++;
if (left > right) break;
}
return result;
}
 
复制代码

 

posted @   daniel456  阅读(50)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
历史上的今天:
2019-01-19 三张图秒懂Redis集群设计原理
2019-01-19 静态代理和动态代理
2019-01-19 spring事务隔离级别、传播机制以及简单配置
点击右上角即可分享
微信分享提示