回形数(java)

回形数(java)_第1张图片

int[][] huiXing = new int[3][3];
		int x = 0;
		int y = 0;
		int value = 1;
		int count = 1; //回形次数
		int hmin = 0;
		int hmax = huiXing.length;
		int lmin = 0;
		int lmax = huiXing.length;
		while(value <= huiXing.length * huiXing.length){
			if(count % 4 == 1){
				while(y < lmax){
					huiXing[x][y] = value;
					y++;
					value++;
				}
				count++;
				hmin++;
//				x = hmin;
				x++;
				y--;//防止角标越界
			}
			if(count % 4 == 2){
				while(x < hmax){
					huiXing[x][y] = value;
					x++;
					value++;
				}
				count++;
				lmax--;
				y--;
				x--;//防止角标越界
			}
			if(count % 4 == 3){
				while(y >= lmin){
					huiXing[x][y] = value;
					y--;
					value++;
				}
				count++;
				hmax--;
				x--;
				y++;//防止角标越界
			}
			if(count % 4 == 0){
				while(x >= hmin){
					huiXing[x][y] = value;
					x--;
					value++;
				}
				count++;
				lmin++;
				y++;;
				x++;//防止角标越界
			}
		}
		
		//打印数组
		for(int i = 0;i < huiXing.length;i++){
			for(int j = 0;j < huiXing[0].length;j++){
				System.out.print(huiXing[i][j] + "\t");
			}
			System.out.println();
		}

你可能感兴趣的:(蓝桥杯,java)