void print2Array(int a[][3], int len) {
for (int i = 0; i < len; i++) {
for (int j = 0; j < len; j++) {
printf("%d ", a[i][j]);
}
printf("\n");
}
}
int main(int argc, const char * argv[]) {
int a1[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int len = sizeof(a1)/sizeof(a1[0]);
print2Array(a1, len);
printf("after rotate\n");
rotateq(a1, len);
return 0;
}
第一种打法
void rotateq(int a[][3], int len) {
int start;
int end;
for (int c = len - 1; c >= 0; c--) {
start = c;
end = 0;
while (start < len) {
printf("%d ", a[end++][start++]);
}
printf("\n");
}
for (int r = 1; r < len; r++) {
int start = r;
int end = 0;
while (start < len) {
printf("%d ", a[end++][start++]);
}
printf("\n");
}
}
第二种打法
void rotateq(int a[][3], int len) {
int start;
int end;
for (int r = len - 1; r >= 0; r--) {
start = 0;
end = r;
while (end < len) {
printf("%d ", a[end++][start++]);
}
printf("\n");
}
for (int c = 1; c < len; c++) {
start = c;
end = 0;
while (start < len) {
printf("%d ", a[end++][start++]);
}
printf("\n");
}
}
字节跳动面试算法题
void rotateq(int a[][3], int len) {
int r = 0, c = 0 ;
int isUp = 1;
while (r >= 0 && r < len && c >= 0 && c < len) {
if (isUp) {
while (r >= 0 && c < len) {
printf("%d ",a[r--][c++]);
}
isUp = 0;
r++;
c--;
if (c == len - 1) {
r++;
}else{
c++;
}
}else{
while (c >= 0 && r < len) {
printf("%d ",a[r++][c--]);
}
isUp = 1;
r--;
c++;
if (r == len - 1) {
c++;
}else{
r++;
}
}
}
}