题目描述:输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下矩阵: 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.
基本思想:用左上和右下的坐标定位出一次要旋转打印的数据,一次旋转打印结束后,往对角分别前进和后退一个单位。
public class PrintMatrix {
public static void main(String[] args) {
// TODO 自动生成的方法存根
int[][] nums2 = {{1,2,3,4},
{5,6,7,8},
{9,10,11,12},
{13,14,15,16}
};
int[][] nums1 = {{1,2},
{5,6},
{9,10},
{13,14}
};
int[][] nums = {{1,2,3,4,5},
{6,7,8,9,10}
};
int left=0,right=0,top=0,bottom=0,i;
int row = nums.length;//行数
int col = nums[0].length;//列数
right = col-1;
bottom = row-1;
if(row==0 || col == 0) return;
while(left<=right && top<=bottom){
for(i=left;i<=right;i++){//从左到右
System.out.print(nums[top][i]+" ");
}
for(i=top+1;i<=bottom;i++){//从上到下
System.out.print(nums[i][right]+" ");
}
for(i=right-1;i>=left;i--){//从右到左
System.out.print(nums[bottom][i]+" ");
}
for(i=bottom-1;i>top;i--){//从下到上
System.out.print(nums[i][left]+" ");
}
left++;right--;bottom--;top++;
}
}
}