Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Name: NTHU Online Judge #10236 - Lab06
- * @author LinChuWen
- * Date: 2014.11.16
- * NCHU EE, Taichung, Taiwan
- *
- * Problem: http://acm.cs.nthu.edu.tw/problem.php?pid=10236
- * Description: Given a number N, we can create an N by N matrix as below:
- * 1 2 3 4 5
- * 16 17 18 19 6
- * 15 24 25 20 7
- * 14 23 22 21 8
- * 13 12 11 10 9
- * In this case, N = 5, and the elements are in order from 1 to N^2 as a clockwise spiral pattern.
- * Note that we always start from the upper left corner.
- */
- import java.util.Scanner;
- public class NTHU_10236_Lab06 {
- private static Scanner input = new Scanner(System.in);
- private static int width;
- public static void main(String[] args){
- System.out.println("Creating an N by N matrix......");
- System.out.print("Please input an integer N: ");
- while(input.hasNext()){
- width = input.nextInt();
- int[][] Matrix = new int[width][width];
- if(width%2==0)
- printMatrix(flipMatrix(buildMatrix(Matrix)));
- else printMatrix(buildMatrix(Matrix));
- } //while end
- } //main end
- private static int[][] buildMatrix( int[][] buildMatrixInput){
- int fillTimes=width;
- int cntFillColumn=0,cntFillRow=0;
- int indexRow=0,indexColumn=0;
- int startRow=0,startColumn=0;
- int cntFlipTimes=0;
- boolean goFlip=false;
- for(int countUp=1;countUp<=width*width;countUp++){
- if(goFlip){
- buildMatrixInput=flipMatrix(buildMatrixInput);
- cntFlipTimes++;
- fillTimes--;
- goFlip=false;
- if(cntFlipTimes%2==0)
- startRow++;
- else startColumn++;
- indexRow=startRow;
- indexColumn=startColumn;
- cntFillColumn=0;cntFillRow=0;
- } //if(goFlip) end
- //fill content into Matrix
- if(cntFillColumn<fillTimes){
- buildMatrixInput[indexRow][indexColumn]=countUp;
- indexColumn++;cntFillColumn++;
- }else{
- indexRow++;cntFillRow++;
- buildMatrixInput[indexRow][indexColumn-1]=countUp;
- if(cntFillRow==fillTimes-1)
- goFlip=true;
- } //fill Matrix end
- } //big for end
- return buildMatrixInput;
- } //buildMatrix() end
- private static int[][] flipMatrix( int[][] flipMatrixInput ){
- int[][] arrayFlip = new int[width][width];
- int cntDown_r,cntDown_c;
- cntDown_r=width-1;
- for(int cntUp_r=0;cntUp_r<width;cntUp_r++){
- cntDown_c=width-1;
- for(int cntUp_c=0;cntUp_c<width;cntUp_c++){
- arrayFlip[cntDown_r][cntDown_c] = flipMatrixInput[cntUp_r][cntUp_c];
- cntDown_c--;
- } //small for end
- cntDown_r--;
- } //big for end
- return arrayFlip;
- } //flipMatrix() end
- private static void printMatrix( int[][] printMatrixInput){
- int cnt1,cnt2;
- for(cnt1=0;cnt1<width;cnt1++){
- for(cnt2=0;cnt2<width;cnt2++){
- System.out.printf("%3d ", printMatrixInput[cnt1][cnt2]);
- } //small for end
- System.out.printf("\n");
- } //big for end
- } //printMatrix() end
- } //class end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement