博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
螺旋矩阵算法
阅读量:6916 次
发布时间:2019-06-27

本文共 1772 字,大约阅读时间需要 5 分钟。

//螺旋输出1-25

public class Sequence {

public static void main(String[] args) {

int n = 5;

// 0:向右,1:向下,2:向左,3:向上

int direction = 0;

// 行,列

int row = 0, col = 0;

int num = 0;


int[] array = new int[n * n];

while (array[row * n + col] == 0) {

num++;

array[row * n + col] = num;

switch (direction) {

case 0:

col++;

break;

case 1:

row++;

break;

case 2:

col--;

break;

case 3:

row--;

break;

}

if (row == n || col == n || row == -1 || col == -1

|| array[row * n + col] != 0) {

direction++;

if (direction == 4)

direction = 0;

switch (direction) {

case 0:

row++;

col++;

break;

case 1:

row++;

col--;

break;

case 2:

row--;

col--;

break;

case 3:

row--;

col++;

break;

}

}

}


for (int i = 0; i < n; i++) {

for (int j = 0; j < n; j++) {

System.out.printf("%-3s", array[i * n + j]);

}

System.out.println();

}

}

}

-----------------------------------------------------------

//矩阵转换

public class TestArray {
public static void main(String[] args) {
int array[][] = { { 22, 18, 36 }, { 27, 34, 58 }, { 12, 51, 32 },
{ 14, 52, 64 } }; // 创建一个4行3列的二维数组
int brray[][] = new int[3][4]; // 创建一个3行4列的数组,用于接收转置后的矩阵
System.out.println("原型矩阵例如以下:");
for (int i = 0; i < array.length; i++) {
// 遍历array数组中的元素
for (int j = 0; j < array[i].length; j++) {
System.out.print(array[i][j] + " ");
}
System.out.println();
}
for (int i = 0; i < array.length; i++) {
// 此时的i是array数组的行。brray的列
for (int j = 0; j < brray.length; j++) {
// 此时的j是array数组的列,brray的行
brray[j][i] = array[i][j]; // 将array数组中的第i行j列的元素赋给brray数组中的j行i列
}
}
System.out.println("\n转置后的矩阵例如以下:");
for (int i = 0; i < brray.length; i++) {
// 遍历转置后brray数组中的元素
for (int j = 0; j < brray[i].length; j++) {
System.out.print(brray[i][j] + " ");
}
System.out.println();
}
}
}

本文转自mfrbuaa博客园博客,原文链接:http://www.cnblogs.com/mfrbuaa/p/5193784.html,如需转载请自行联系原作者

你可能感兴趣的文章
SQLServer学习视频系列
查看>>
maven仓库及镜像
查看>>
PHP中include()与require()的区别说明
查看>>
elasticsearch相关资料
查看>>
SQL Server 输出 XML
查看>>
Tiffany And Co Rings provide a variety of necklace
查看>>
使用handlebars-template模板来展示数据
查看>>
hibernate N+1问题
查看>>
CA是如何颁发证书的
查看>>
浅谈移动端 View 的显示过程
查看>>
方差分析引论
查看>>
时间序列的概念、种类及编制原则
查看>>
NA笔记-帧中继2-P to P_EIGRP
查看>>
计算距离
查看>>
数据结构---哈希表(KV模式)(除留余数法)
查看>>
spark-local 模式 提示 /tmp/hive hdfs 权限不够的问题
查看>>
我的友情链接
查看>>
MYSQL-5.7.11安装记录
查看>>
我的友情链接
查看>>
检查文件下面时候存在ini文件
查看>>