Java-螺旋方阵
2024-09-15 16:18:53
用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("");
}
}
最新文章
- [ActionScript 3.0] 对代码加密的有效方法
- [VIM] 格式化代码
- 《Java核心技术卷一》笔记 多线程同步(底层实现)
- LeetCode Fraction to Recurring Decimal
- wpfのuri(让你完全明白wpf的图片加载方式以及URI写法)
- C#扫描仪编程、条形码识别编程资料
- [转载]mysql插入大量数据
- Android学习----Activity
- flume日志采集框架使用
- JavaWeb 后端 <;十四>; 文件上传下载
- IDEA Default模式下的常用快捷键
- HTML页面全屏/退出全屏
- 在CMD命令下安装nexus报错和启动的问题
- 全网最详细的基于Ubuntu14.04/16.04 + Anaconda2 / Anaconda3 + Python2.7/3.4/3.5/3.6安装Tensorflow详细步骤(图文)(博主推荐)
- 阿里云centos安装docker-engine实践
- 03.设计模式_抽象工厂模式(Abstract Fcatory)
- JS 相关记录(scrollTo,JSON)
- js常用总结
- 面试Tips
- [DeeplearningAI笔记]卷积神经网络4.11一维和三维卷积
热门文章
- Codeforces Round #370 (Div. 2) A B C 水 模拟 贪心
- .net中创建xml文件
- js图片无缝滚动代码
- CSS+DIV常用命名
- JavaWeb学习记录(二十)——Model1模式(javaBean+jsp)实现简单计算器案例
- LNMP-查看安装编译时参数
- media type与media query
- [Unity 5.2] The imported type `UnityEngine.Advertisements.ShowResult&#39; is defined multiple times
- OpenJudge计算概论-鸡尾酒疗法
- js列表分页