def reshape_matrix(matrix, r, c):
    rows = len(matrix)
    cols = len(matrix[0]) if rows else 0
    if rows * cols != r * c:
        return matrix
    output = [[0] * c for _ in range(r)]
    index = 0
    for row in matrix:
        for value in row:
            output[index // c][index % c] = value
            index += 1
    return output
