演算法-旋轉映像(矩陣處理)

來源:互聯網
上載者:User

標籤:i++   nbsp   col   temp   映像   ima   bsp   矩陣   lint   

今天在lintCode做了一道題,自己想了一下做法,做出來,但是覺得有必要記錄下來。

題意:

給定一個N×N的二維矩陣表示映像,90度順時針旋轉映像。

範例:

給出一個矩形[[1,2],[3,4]],90度順時針旋轉後,返回[[3,1],[4,2]]

挑戰:

能否在原地完成?

1.解題思路

  這個題乍一看懵逼,其實非常的簡單。下面我用圖來表示解題思路:

2.代碼

 1     public void rotate(int[][] matrix) { 2         if (matrix.length == 0 || matrix[0].length == 0) { 3             return; 4         } 5         //順時針旋轉270度 6         for (int i = 0; i < matrix.length; i++) { 7             for (int j = 0; j < i; j++) { 8                 int temp = matrix[i][j]; 9                 matrix[i][j] = matrix[j][i];10                 matrix[j][i] = temp;11             }12         }13         //逆時針旋轉180度14         for(int i = 0; i < matrix.length; i++) {15             for(int j = 0; j < matrix[0].length / 2; j++) {16                 int temp = matrix[i][j];17                 matrix[i][j] = matrix[i][matrix[0].length - 1 - j];18                 matrix[i][matrix[0].length - 1 - j] = temp;19             }20         }21     }

 

演算法-旋轉映像(矩陣處理)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.