|
| 1 | +/* |
| 2 | + * Copyright (C) 2020, Saul Lawliet <october dot sunbathe at gmail dot com> |
| 3 | + * All rights reserved. |
| 4 | + * |
| 5 | + * 由于每一行都是有序的, 所以可以从右下角往左上角查找 |
| 6 | + */ |
| 7 | + |
| 8 | +#include <stdlib.h> /* malloc(), free() */ |
| 9 | +#include "c/data-structures/array.h" |
| 10 | +#include "c/test.h" |
| 11 | + |
| 12 | +struct BinaryMatrix { |
| 13 | + arrayEntry *e; |
| 14 | + int (*get)(struct BinaryMatrix *, int, int); |
| 15 | + int *(*dimensions)(struct BinaryMatrix *); |
| 16 | +}; |
| 17 | + |
| 18 | +int get(struct BinaryMatrix *matrix, int x, int y) { |
| 19 | + return ((int **)arrayValue(matrix->e))[x][y]; |
| 20 | +} |
| 21 | + |
| 22 | +int *dimensitons(struct BinaryMatrix *matrix) { |
| 23 | + int *dimensitons = malloc(sizeof(int) * 2); |
| 24 | + dimensitons[0] = arrayRow(matrix->e); |
| 25 | + dimensitons[1] = arrayCol(matrix->e); |
| 26 | + return dimensitons; |
| 27 | +} |
| 28 | + |
| 29 | +/** |
| 30 | + * // This is the BinaryMatrix's API interface. |
| 31 | + * // You should not implement it, or speculate about its implementation |
| 32 | + * struct BinaryMatrix { |
| 33 | + * int (*get)(struct BinaryMatrix*, int, int); |
| 34 | + * int* (*dimensions)(struct BinaryMatrix*); |
| 35 | + * }; |
| 36 | + */ |
| 37 | +int leftMostColumnWithOne(struct BinaryMatrix *matrix) { |
| 38 | + int *dimensitons = matrix->dimensions(matrix); |
| 39 | + int x = dimensitons[0] - 1, y = dimensitons[1] - 1, y1 = y; |
| 40 | + free(dimensitons); |
| 41 | + while (x >= 0 && y >= 0) { |
| 42 | + matrix->get(matrix, x, y) == 0 ? --x : --y; |
| 43 | + } |
| 44 | + return x == -1 && y == y1 ? -1 : y + 1; |
| 45 | +} |
| 46 | + |
| 47 | +void test(int expect, char *s) { |
| 48 | + arrayEntry *e = arrayParse2D(s, ARRAY_INT); |
| 49 | + struct BinaryMatrix matrix = {e, get, dimensitons}; |
| 50 | + EXPECT_EQ_INT(expect, leftMostColumnWithOne(&matrix)); |
| 51 | + arrayFree(e); |
| 52 | +} |
| 53 | + |
| 54 | +int main(void) { |
| 55 | + test(0, "[[0,0],[1,1]]"); |
| 56 | + test(1, "[[0,0],[0,1]]"); |
| 57 | + test(-1, "[[0,0],[0,0]]"); |
| 58 | + test(1, "[[0,0,0,1],[0,0,1,1],[0,1,1,1]]"); |
| 59 | + |
| 60 | + return testOutput(); |
| 61 | +} |
0 commit comments