zoukankan      html  css  js  c++  java
  • Cracking the coding interview--Q1.6

    原文:

    Given an image represented by an NxN matrix, where each pixel in the image is 4 bytes, write a method to rotate the image by 90 degrees. Can you do this in place?

    译文

    给一个NxN的矩阵,写一个函数把矩阵旋转90度。 并且要求在原矩阵上进行操作,即不允许开辟额外的存储空间。

    解答

    (一)Hawstein在他的Blog中http://hawstein.com/posts/1.6.html介绍的方法是:可以分两步走。 第一步交换主对角线两侧的对称元素,第二步交换第i行和第n-1-i行,即得到结果。 看图示:

    原图:           第一步操作后:   第二步操作后:
    1 2 3 4         1 5 9 13        4 8 12 16
    5 6 7 8         2 6 10 14       3 7 11 15
    9 10 11 12      3 7 11 15       2 6 10 14
    13 14 15 16     4 8 12 16       1 5 9 13

    (二)在可以直接考虑旋转,四个方向的元素依次移动。

    public class Main {
    
        public static void rotate(int[][] mat, int n) {
            for (int i = 0; i < n / 2; i++) {
                for (int j = i; j < n - 1 - i; j++) {
                    // save top
                    int temp = mat[i][j];
                    // left --> top
                    mat[i][j] = mat[n - 1 - j][i];
                    // down --> left
                    mat[n - 1 - j][i] = mat[n - 1 - i][n - 1 - j];
                    // right --> down
                    mat[n - 1 - i][n - 1 - j] = mat[j][n - 1 - i];
                    // top --> right
                    mat[j][n - 1 - i] = temp;
                }
            }
        }
    
        public static void main(String args[]) {
            int a[][] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 },
                    { 13, 14, 15, 16 } };
            for (int i = 0; i < 4; ++i) {
                for (int j = 0; j < 4; ++j)
                    System.out.print(a[i][j] + " ");
                System.out.println();
            }
            rotate(a, 4);
            System.out.println("------------------");
            for (int i = 0; i < 4; ++i) {
                for (int j = 0; j < 4; ++j)
                    System.out.print(a[i][j] + " ");
                System.out.println();
            }
        }
    }
  • 相关阅读:
    route命令
    linux下限制ip访问
    linux安装oracle客户端
    Upgrading to Kentico 12
    online youtube subtitle downloader
    Driving continuous quality of your code with SonarCloud
    炉石传说 乱斗模式 三足鼎立
    Behavior-driven development
    TestNG like unit testing framework in C# (C sharp)
    Windows 10 & 8: Install Active Directory Users and Computers
  • 原文地址:https://www.cnblogs.com/giraffe/p/3186697.html
Copyright © 2011-2022 走看看