Skip to content

Latest commit

 

History

History
106 lines (89 loc) · 3.14 KB

48.rotate-image.md

File metadata and controls

106 lines (89 loc) · 3.14 KB

旋转图像

题目

思路

根据题意, 我们先将图片分为四个部分.

分为四个部分

分为四个部分后, 对第一个部分里的所有数字进行替换, 从而实现旋转.

  1. 步骤一
  2. 步骤二
  3. 步骤三
  4. 步骤四

根据步骤, 很容易理解无非就是从坐标里查找剩下的几个坐标集, 而后进行替换.

比如说

  1. [0, 0] -> [0, 3] -> [3, 3] -> [3, 0] -> [0, 0]
  2. [0, 1] -> [1, 3] -> [3, 2] -> [2, 0] -> [0, 1]
  3. [1, 0] -> [0, 2] -> [2, 3] -> [3, 1] -> [1, 0]
  4. [1, 1] -> [1, 2] -> [2, 2] -> [2, 1] -> [1, 1]

这是列数为偶数的时候的情况, 如果列数为奇数时, 位于中间线的数字会经过两次计算, 因此要排除一次计算即可.

/**
 * @param {number[][]} matrix
 * @return {void} Do not return anything, modify matrix in-place instead.
 */
var rotate = function(matrix) {
  let length = matrix.length
  const middle = Math.ceil(length / 2)
  length = length - 1
  for (let i = 0; i < middle; i++) {
    for (let j = 0; j < middle; j++) {
      // 奇数列数的时候 要排除一次计算
      if (middle * 2 !== (length + 1) && middle - 1 === i) {
        continue
      }
      const tmp = matrix[i][j]
      matrix[i][j] = matrix[length - j][i]
      matrix[length - j][i] = matrix[length - i][length - j]
      matrix[length - i][length - j] = matrix[j][length - i]
      matrix[j][length - i] = tmp
    }
  }
};
class Solution {
  /**
   * @param Integer[][] $matrix
   * @return NULL
   */
  function rotate(&$matrix) {
    $length = count($matrix);
    $middle = ceil($length / 2);
    $length = $length - 1;
    for ($i = 0; $i < $middle; $i++) {
      for ($j = 0; $j < $middle; $j++) {
        if ($middle * 2 != ($length + 1) && $middle - 1 == $i) {
          continue;
        } else {
          $tmp = $matrix[$i][$j];
          $matrix[$i][$j] = $matrix[$length - $j][$i];
          $matrix[$length - $j][$i] = $matrix[$length - $i][$length - $j];
          $matrix[$length - $i][$length - $j] = $matrix[$j][$length - $i];
          $matrix[$j][$length - $i] = $tmp;
        }
      }
    }
  }
}
class Solution {
  public void rotate(int[][] matrix) {
    double matrixLength = matrix.length;

    int middle = (int)Math.ceil(matrixLength / 2);

    int length = new Double(matrixLength).intValue() - 1;

    for (int i = 0; i < middle; i++) {
      for (int j = 0; j < middle; j++) {
        if (middle * 2 != (length + 1) && middle - 1 == i) {
          continue;
        }
        int tmp = matrix[i][j];
        matrix[i][j] = matrix[length - j][i];
        matrix[length - j][i] = matrix[length - i][length - j];
        matrix[length - i][length - j] = matrix[j][length - i];
        matrix[j][length - i] = tmp;
      }
    }
  }
}