摘要
一、模拟算法原理与解题方法
二、顺时针打印矩阵
顺时针打印矩阵_牛客题霸_牛客网
解题思路:递归的思想和非递归的思想相差不大,递归是首先打印最外层的元素,将内层的矩阵作为一个全新的矩阵进行递归。对于每层,从左上方开始以顺时针的顺序遍历所有元素。假设当前层的左上角位于 (top,left),右下角位于(bottom,right),按照如下顺序遍历当前层的元素。
1、从左到右遍历上侧元素,依次为(top,left) 到(top,right)。
2、从上到下遍历右侧元素,依次为(top+1,right) 到 (bottom,right)。
3、如果 left bottom) {
return;
}
// 从右到左
for (int i = right; i >= left; i--) {
res.add(matrix[bottom][i]);
}
bottom--;
if (left > right || top > bottom) {
return;
}
// 从下到上
for (int i = bottom; i >= top; i--) {
res.add(matrix[i][left]);
}
left++;
// 递归
print(left, right, top, bottom, matrix);
}
}
