`

打印自定义格式的N宫格

阅读更多
输出n宫格,要求是数字从1开始,顺时针绕着宫格周围逐渐增大,到了左下角后,开始从左到右输出倒数第二行,第三行...的数据,直到填满宫格。

private static void print(int n) {
	StringBuilder sb = new StringBuilder();
    // Print the output via iterating each row
	myloop: for (int i = 1; i <= n; i++) {

    // Process the first row
	if (i == 1) {
		for (int j = 1; j <= n; j++)
			sb.append(j).append("\t");
		sb.append("\r\n");
		continue myloop;
	}
	
    // Process the last row
	if (i == n) {
		for (int j = 1; j <= n; j++)
			sb.append(3 * n - 1 - j).append("\t");
		sb.append("\r\n");
		break myloop;
	}
	
    // Process other rows
	for (int j = 1; j <= n; j++) {
            // Process the last column of the other rows
		if (j == n) {
			sb.append(n + i - 1).append("\r\n");
			continue myloop;
		}
		sb.append(n * n - (i - 1) * (n - 1) + j).append("\t");
	}
}
System.out.println(sb.toString());
}


如果n为3,输出的结果如下:
1 2 3
8 9 4
7 6 5
如果n为4,输出的结果如下:
1 2 3 4
14 15 16 5
11 12 13 6
10 9 8 7
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics