用Java实现螺旋方阵

螺旋方阵:是指呈螺旋状的矩阵。

具体实现如下:

public void screwMatrix() {
System.out.print("请输入数字:");
Scanner input = new Scanner(System.in);
int number = input.nextInt(); int[][] matrix = new int[number][number];
int max = number * number;
int row = 0, col = 0;
int direction = 0;
for (int j = 1; j <= max; j++) {
matrix[row][col] = j;
switch (direction) {
case 0 :
if (col + 1 >= number || matrix[row][col + 1] > 0) {
direction += 1;
direction %= 4;
row += 1;
} else {
col = col + 1;
}
break;
case 1 :
if (row + 1 >= number || matrix[row + 1][col] > 0) {
direction += 1;
direction %= 4;
col -= 1;
} else {
row = row + 1;
}
break;
case 2 :
if (col - 1 < 0 || matrix[row][col - 1] > 0) {
direction += 1;
direction %= 4;
row = row - 1;
} else {
col = col - 1;
}
break;
case 3 :
if (row - 1 < 0 || matrix[row - 1][col] > 0) {
direction += 1;
direction %= 4;
col += 1;
} else {
row = row - 1;
}
break;
default :
System.out.println("ERROR");
System.exit(0);
}
}
for (int j = 0; j < number; j++) {
for (int k = 0; k < number; k++) {
// 判断输出最大数的长度
int size = ((number * number) + "").length(); for (int i = 0; i <= (size - (matrix[j][k] + "").length() + 1); i++) {
System.out.print(" ");
}
System.out.print(matrix[j][k]);
}
System.out.println("");
}
}

最新文章

  1. [ActionScript 3.0] 对代码加密的有效方法
  2. [VIM] 格式化代码
  3. 《Java核心技术卷一》笔记 多线程同步(底层实现)
  4. LeetCode Fraction to Recurring Decimal
  5. wpfのuri(让你完全明白wpf的图片加载方式以及URI写法)
  6. C#扫描仪编程、条形码识别编程资料
  7. [转载]mysql插入大量数据
  8. Android学习----Activity
  9. flume日志采集框架使用
  10. JavaWeb 后端 &lt;十四&gt; 文件上传下载
  11. IDEA Default模式下的常用快捷键
  12. HTML页面全屏/退出全屏
  13. 在CMD命令下安装nexus报错和启动的问题
  14. 全网最详细的基于Ubuntu14.04/16.04 + Anaconda2 / Anaconda3 + Python2.7/3.4/3.5/3.6安装Tensorflow详细步骤(图文)(博主推荐)
  15. 阿里云centos安装docker-engine实践
  16. 03.设计模式_抽象工厂模式(Abstract Fcatory)
  17. JS 相关记录(scrollTo,JSON)
  18. js常用总结
  19. 面试Tips
  20. [DeeplearningAI笔记]卷积神经网络4.11一维和三维卷积

热门文章

  1. Codeforces Round #370 (Div. 2) A B C 水 模拟 贪心
  2. .net中创建xml文件
  3. js图片无缝滚动代码
  4. CSS+DIV常用命名
  5. JavaWeb学习记录(二十)——Model1模式(javaBean+jsp)实现简单计算器案例
  6. LNMP-查看安装编译时参数
  7. media type与media query
  8. [Unity 5.2] The imported type `UnityEngine.Advertisements.ShowResult&#39; is defined multiple times
  9. OpenJudge计算概论-鸡尾酒疗法
  10. js列表分页