矩阵的环形打印和旋转

 

矩阵的环形打印

思想是全局到微观,就是扣整个过程的共同点。

假设有一个矩阵 arr  { { 1, 2, 3, 4 },

                                    {  5, 6, 7, 8 },

                                   { 9, 10, 11, 12 }, 

                                  { 13, 14, 15, 16 } }

需要把它顺时针打印。

可以先确定两个点,一个是左上的一个点假设为(tR,tL) ,也就是上面的    1  。另一个是右下的一个点假设为(bR,bL) ,也就是上面的16.

我们只需要在打印的时候上面的  tL循环递减,右边边的tR增加,下面的 tL增加,左边tR递减。

他们的边界是小于当前递减(递增)行(列)的最大值,也就是少一个。

完成第一圈,然后再进行第二圈,第二圈把左上的顶点的tR,tL 都加一,右下的bR,bL都减一,知道tR == bR  和 tL==bL 为止。

但是也要考虑特殊情况,比如给的矩阵只有一行或者一列,所以需要判断,当为一行或者一列的时候直接输出。

下面看代码:

package com.none;

public class PrintArround {
	public static void PrintAll(int [][] arr){
		int tC = 0;
		int tL = 0;
		int bC = arr.length - 1;
		int bL = arr[0].length - 1;
		while(tC <= bC && tL <= bL){
			PrintCode(arr, tC++, tL++, bC--, bL--);
		}
	}
	
	public static void PrintCode(int [][] arr,int tC,int tL,int bC,int bL){
		/*
		 * tC 左上的行    
		 * tL 左上的列
		 * bC 右下的行
		 * bL 右下的列 
		 * */
		if(tC == bC){  //只有一行的情况
			for(int i = tL ;i <= bL ;i++){
				System.out.println(arr[tC][i]+"\t");
			}
		}else if(tL == bL ){  //只有一列的情况  
			for(int i = tC ;i <= bC ;i++ ){
				System.out.println(arr[i][tL]+"\t");
			}
		}else{
			int curL = tL ;  //等于左上的行
			int curC = tC ;  //等于左上的列
			while(bC != curC){   // 向右输出
				System.out.println(arr[tL][curC] + "\t"); 
				curC++ ;
			}
			while(bL != curL){  //向下输出
				System.out.println(arr[curL][bC] + "\t");
				curL++;
			}
			while(curC != tC){  //向左输出
				System.out.println(arr[bL][curC]+"\t");
				curC--;
			}
			while(curL != tL ){  //向上输出
				System.out.println(arr[curL][tC]+"\t");
				curL -- ;
			}
		}
	}
	public static void main(String[] args) {
//		int [][] arr = new int[][]{{1},{2},{3},{4},{5},{6},{7},{8},{9},{10},{11},{12}};
		int [][] arr = new int[][]{ { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 },
			{ 13, 14, 15, 16 } };
		PrintAll(arr);
	}
}

 矩阵的旋转

矩阵的旋转和环线打印的思想一样。

直接上代码:

package com.none;

public class RandCode {
	public static void getRand(int[][] m, int tR, int tC, int dR, int dC) {
		int times = dC - tC; 
		int tmp = 0;
		for (int i = 0; i != times; i++) {
			tmp = m[tR][tC + i];
			m[tR][tC + i] = m[dR - i][tC];
			m[dR - i][tC] = m[dR][dC - i];
			m[dR][dC - i] = m[tR + i][dC];
			m[tR + i][dC] = tmp;
		}
	}
	public static void Rand(int[][] arr){
		int tR = 0 ;
		int tL = 0 ;
		int bR = arr.length - 1 ;
		int bL = arr[0].length - 1;
		while(tR <= bR && tL <= bL){
			getRand(arr,tR++,tL++,bR--,bL--);
		}
	}
	public static void main(String[] args) {
		int [][] arr = new int[][]{ { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 },
				{ 13, 14, 15, 16 } };
		Rand(arr);
		for(int i = 0;i<arr.length;i++){
			for(int j = 0 ;j<arr[i].length;j++){
				System.out.print(arr[i][j]+"\t");
			}
			System.out.println();
		}
	}
}

 

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务