螺旋矩阵算法

简介:
//螺旋输出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,如需转载请自行联系原作者

相关文章
|
4月前
|
存储 机器学习/深度学习 算法
【算法训练-数组 三】【数组矩阵】螺旋矩阵、旋转图像、搜索二维矩阵
【算法训练-数组 三】【数组矩阵】螺旋矩阵、旋转图像、搜索二维矩阵
70 0
|
4月前
|
算法
|
3月前
|
存储 算法 数据挖掘
python5种算法模拟螺旋、分层填充、递归、迭代、分治实现螺旋矩阵ll【力扣题59】
python5种算法模拟螺旋、分层填充、递归、迭代、分治实现螺旋矩阵ll【力扣题59】
|
3月前
|
存储 算法 数据挖掘
螺旋矩阵 II:从理论到实践的五种算法解析
螺旋矩阵 II:从理论到实践的五种算法解析
|
3月前
|
算法 机器人 数据挖掘
LeetCode题目54:螺旋矩阵【python4种算法实现】
LeetCode题目54:螺旋矩阵【python4种算法实现】
|
10月前
|
算法
代码随想录算法训练营第二天 | LeetCode 977.有序数组的平方、209.长度最小的子数组、59. 螺旋矩阵 II
代码随想录算法训练营第二天 | LeetCode 977.有序数组的平方、209.长度最小的子数组、59. 螺旋矩阵 II
51 0
|
10月前
|
算法 索引
代码随想录算法训练营第二天 |977.有序数组平方,209.长度最小的字数组,59.螺旋矩阵
代码随想录算法训练营第二天 |977.有序数组平方,209.长度最小的字数组,59.螺旋矩阵
|
算法 索引
代码随想录算法训练营第二天| 977.有序数组的平方 ,209.长度最小的子数组 ,59.螺旋矩阵II ,总结
代码随想录算法训练营第二天| 977.有序数组的平方 ,209.长度最小的子数组 ,59.螺旋矩阵II ,总结
|
人工智能 算法
【数据结构与算法】数组2:双指针法 & 二分法(螺旋矩阵)
【数据结构与算法】数组2:双指针法 & 二分法(螺旋矩阵)
88 0
|
算法 Java
【算法】给你一个数字算出螺旋矩阵,要不要来试一试?
给你一个正整数 n ,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的
82 2
【算法】给你一个数字算出螺旋矩阵,要不要来试一试?