• 螺旋矩阵算法


    //螺旋输出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(" 转置后的矩阵例如以下:");
    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();
    }
    }
    }

  • 相关阅读:
    API Hook完全手册
    ASP.NET页面刷新的实现方法
    ASP.NET验证码
    ASP.NET优化性能的方法
    Asp.net中Server.Transfer,Server.Execute和Response.Redirect的区别
    FireFox新标签页打开搜索和书签
    win10里如何在中文输入法里添加美式键盘
    Sublime Text 3中文乱码问题解决
    Win2008 r2 IIS7.5出现“FastCGI进程最近常常失败。请过一会再尝试此请求”的解决方法
    Sublime Text 3中设置不记住上次打开的文件
  • 原文地址:https://www.cnblogs.com/mfrbuaa/p/5193784.html
Copyright © 2020-2023  润新知