My answer: Logic here is that, given specific level, rotate values at that level one by one. The key thing is to find out index of next one to be swapped. One hand-draw picture will be attached. Be careful of that no need to rotate the last element of that level.
class Solution { public void rotate(int[][] matrix) { if (matrix == null || matrix.length < 1 || matrix.length != matrix[0].length || matrix.length == 1) { return; } int level = 0; do { for (int j = level; j < matrix.length - 1 - level; j ++) { int right = matrix[j][matrix.length - 1 - level]; matrix[j][matrix.length - 1 - level] = matrix[level][j]; int bottom = matrix[matrix.length - 1 - level][matrix.length - 1 - j]; matrix[matrix.length - 1 - level][matrix.length - 1 - j] = right; int left = matrix[matrix.length - 1 - j][level]; matrix[matrix.length - 1 - j][level] = bottom; matrix[level][j] = left; } level ++; } while(2* (level + 1) <= matrix.length); } }
Attached image explaining how to find where to swap:
No comments:
Post a Comment