Rotate an N * N matrix clockwise 90 degrees.

Assumptions

  • The matrix is not null and N > = 0

Examples

{ {1, 2, 3}

{8, 9, 4},

{7, 6, 5} }

after rotation is

{ {7, 8, 1}

{6, 9, 2},

{5, 4, 3} }

Solution: 用start, end标记边界,注意index关系

  public void rotate(int[][] matrix) {
    int start = 0, end = matrix.length - 1;
    while (start < end) {
    //注意i从0到end - start
      for (int i = 0; i < end - start; i++) {
        int temp = matrix[start][start + i];
        matrix[start][start + i] = matrix[end - i][start];
        matrix[end - i][start] = matrix[end][end - i];
        matrix[end][end - i] = matrix[start + i][end];
        matrix[start + i][end] = temp;
      }
      start++;
      end--;
    }
  }

results matching ""

    No results matching ""