打印回型矩陣

package circlenum;



/**
 * 
 * @author xcm
 *	騰訊的在線筆試題,輸入一個矩(方)陣的大小n,輸出其回型矩(方)陣,例如
 *  輸入3,輸出  
 *  1	2	3	
	8	9	4	
	7	6	5
	輸入4,輸出
	1	2	3	4	
	12	13	14	5	
	11	16	15	6	
	10	9	8	7
	
	具體的思路就是依次按照四個方向遍歷每個圈
	
 */
public class CirCleNumber {
	public static void main(String[] args) {
		int n = 4;//須要改爲標準輸入System.in
		if (n == 1) {
			System.out.println(1);
			return;
		}
		int[][] data = new int[n][n];
		int i = 0, j = 0;
		int num = 1;
		int direction = 1;//方向
		int circle = 0;//第幾圈,從0開始
		while (num <= n * n) {
			data[i][j] = num;
			num++;
			if (j < n - 1 && data[i][j + 1] == 0 && direction == 1) {
				j++;
				continue;
			} else {
				direction = 2;
			}

			if (i < n - 1 && data[i + 1][j] == 0 && direction == 2) {
				i++;
				continue;
			} else {
				direction = 3;
			}

			if (j > 0 && data[i][j - 1] == 0 && direction == 3) {
				j--;
				continue;
			} else {
				direction = 4;
			}

			if (i > 0 && data[i - 1][j] == 0 && direction == 4) {
				i--;
				continue;
			} else {
				circle++;
				i = circle;//到下一圈
				j = circle;//到下一圈
				direction = 1;
			}
		}
		print(data);
	}

	public static void print(int[][] data) {
		int n = data.length;
		for (int i = 0; i < n; i++) {
			for (int j = 0; j < n; j++) {
				System.out.print(data[i][j] + "\t");
				if ((j + 1) % n == 0) {
					System.out.println();
				}
			}
		}
		System.out.println();
	}

}
相關文章
相關標籤/搜索