leetcode 48. Rotate Image 矩阵旋转

来源:互联网 发布:线切割编程要证明的 编辑:程序博客网 时间:2024/05/22 07:02

You are given an n x n 2D matrix representing an image.

Rotate the image by 90 degrees (clockwise).

Note:
You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.

这道题就是输一个n*n的矩阵顺时针旋转90度,然后求矩阵的元素。矩阵转置是相当于旋转180度,所以比划一下,然后直接做逆序处理或者转置处理等等操作既可以得到答案。

代码如下:

import java.awt.print.Printable;public class Solution {    public void rotate(int[][] matrix)     {        if(matrix==null || matrix.length<=0)            return ;        int row=matrix.length;        int col=matrix[0].length;            //先做矩阵转置        for(int i=0;i<row;i++)        {            for(int j=i+1;j<col;j++)            {                int tmp=matrix[i][j];                matrix[i][j]=matrix[j][i];                matrix[j][i]=tmp;            }        }        //顺时针旋转90,那么针对每一行做逆序处理        //逆时针旋转90,那么将针对每一列做逆序处理        for(int i=0;i<row;i++)        {            int beg=0,end=col-1;            while(beg<end)            {                int tmp=matrix[i][beg];                matrix[i][beg]=matrix[i][end];                matrix[i][end]=tmp;                beg++;                end--;            }        }    }   }

这道题看起来很简单,但是仔细去做的时候发现有点想不清楚,这就告诉我们说遇到问题需想清楚,可以先做矩阵转置,然后在做其他的

代码如下:

#include <iostream>#include <vector>using namespace std;class Solution {public:    void rotate(vector<vector<int>>& matrix)     {        if (matrix.size() <= 1)            return;        for (int i = 0; i < matrix.size(); i++)        {            for (int j = i+1; j < matrix.size(); j++)            {                int tmp = matrix[i][j];                matrix[i][j] = matrix[j][i];                matrix[j][i] = tmp;            }        }        for (int i = 0; i < matrix.size(); i++)        {            int beg = 0, end = matrix.size() - 1;            while (beg < end)            {                int tmp = matrix[i][beg];                matrix[i][beg] = matrix[i][end];                matrix[i][end] = tmp;                beg++;                 end--;            }        }        return;    }};
原创粉丝点击