zoukankan      html  css  js  c++  java
  • 算法——旋转正方形矩阵

    给定一个整形正方形矩阵arr,请把改矩阵调整成顺时针选择90度的样子。

    示例:
    1 2 3 
    4 5 6 
    7 8 9 
    旋转后:
    7 4 1 
    8 5 2 
    9 6 3 
    package suanfa;
    
    public class demo3 {
        public static void main(String[] args) {
            int[][] arr={{1,2,3},{4,5,6},{7,8,9}};
            xuanze(arr);
        }
        private static void xuanze(int[][] arr) {
            int a=0,b=0,c=arr.length-1,d=arr[0].length-1;//初始化左上坐标(a,b)和右下坐标(c,d)
            while(a<c&&b<d){//两个坐标相遇或超过时结束循环
                //先旋转外圈,再旋转内圈
                //两个坐标向中心走
                rotate(arr,a++,b++,c--,d--);
            }
        }
    
        private static void rotate(int[][] arr, int a, int b, int c, int d) {
            int count=a;//每条边的旋转起点
            while(count<d-b){//限制旋转的终点
                int temp=arr[a][b+count];
                arr[a][b+count]=arr[c-count][b];
                arr[c-count][b]=arr[c][d-count];
                arr[c][d-count]=arr[a+count][d];
                arr[a+count][d]=temp;
                count++;
            }
        }
    
    }
  • 相关阅读:
    服务器搭建Git
    BGP协议详解
    以太坊
    燃 * & *
    UML类图解析
    day8.文件操作
    python面试题汇总
    day5.字典
    day5.类型汇总
    day3,4总结程序
  • 原文地址:https://www.cnblogs.com/huozhonghun/p/9862317.html
Copyright © 2011-2022 走看看