LeetCode:Rotate Image

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

Rotate the image by 90 degrees(clockwise).

Follow up: Could you do this in-place?

解题思路:

暴力法:从外到内一圈一圈地转,不过这个方法效率太低,比较慢。

分析法:首先沿着副对角线翻转一次,然后沿着水平中线翻转一次。


代码如下:

void rotate(vetor<vector<int>>& matrix) {
	const int n = matrix.size();
	for (itn i=0; i<n; ++i) {
		for (int j=0; j<n-i; ++j) { //沿着副对角线反转
			swap (matrix[i][j], matrix[n-1-j][n-1-i]);
		}
	}
	for (int i=0; i<n/2; ++i) { //沿着水平中线反转
		for (int j=0; i<n; ++j) {
			swap (matrix[i][j], matrix[n-1-i][j]);
		}
	}
}

当然也可以先沿着水平中线翻转一次,然后沿着主对角线再翻转一次。

代码如下:

void rotate(vetor<vector<int>>& matrix) {
	const int n = matrix.size();

	for (int i=0; i<n/2; ++i) { //沿着水平中线反转
		for (int j=0; i<n; ++j) {
			swap (matrix[i][j], matrix[n-1-i][j]);
		}
	}

	for (itn i=0; i<n; ++i) {
		for (int j=i+1; j<n; ++j) { //沿着主对角线反转
			swap (matrix[i][j], matrix[j][i]);
		}
	}
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章