Leet Code 48 Rotate Image - 旋转图片 - Java
2016-06-23 00:00
169 查看
摘要: Leet Code 48 Rotate Image - 旋转图片 - Java
问题原始链接 https://leetcode.com/problems/rotate-image
给定一个 n*n 的二维数组,表示一张图片,把该图片顺时针旋转90度。
问题原始链接 https://leetcode.com/problems/rotate-image
给定一个 n*n 的二维数组,表示一张图片,把该图片顺时针旋转90度。
public class Solution { public static void rotate(int[][] matrix) { if (matrix == null || matrix.length <= 1) { return; } for (int i = 0; i < matrix.length / 2; i++) { rotateCircle(matrix, i); } } private static void rotateCircle(int[][] matrix, int i) { int step = matrix.length - 1 - i * 2; for (int j = i; j < matrix.length - 1 - i; j++) { int nextRow = -1; int nextCol = -1; int curRow = i; int curCol = j; int temp = matrix[curRow][curCol]; do { nextRow = getNextRow(matrix, i, step, curRow, curCol); nextCol = getNextCol(matrix, i, step, curRow, curCol); int t = matrix[nextRow][nextCol]; matrix[nextRow][nextCol] = temp; temp = t; curRow = nextRow; curCol = nextCol; } while (nextRow != i || nextCol != j); } } private static int getNextRow(int[][] matrix, int n, int step, int i, int j) { int max = matrix.length - 1 - n; if (i == n && j >= n && j < max) { return j + step <= max ? n : n + (j + step - max); } if (i >= n && i < max && j == max) { return max; } if (i == max && j > n && j <= max) { return j - step >= n ? max : max - (n - (j - step)); } if (i > n && i <= max && j == n) { return n; } return i; } private static int getNextCol(int[][] matrix, int n, int step, int i, int j) { int max = matrix.length - 1 - n; if (i == n && j >= n && j < max) { return max; } if (i >= n && i < max && j == max) { return i + step <= max ? max : max - (i + step - max); } if (i == max && j > n && j <= max) { return n; } if (i > n && i <= max && j == n) { return i - step >= n ? n : n + (n - (i - step)); } return j; } }
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解