|
| 1 | +def hungry_rabbit_util(garden, row, col): |
| 2 | + max = 0 |
| 3 | + next_row = None |
| 4 | + next_col = None |
| 5 | + |
| 6 | + for r, c in [[-1, 0], [1, 0], [0, -1], [0, 1]]: |
| 7 | + if row + r >= 0 and row + r < len(garden) and \ |
| 8 | + col + c >= 0 and col + c < len(garden[row]): |
| 9 | + if garden[row + r][col + c] > max: |
| 10 | + max = garden[row + r][col + c] |
| 11 | + next_row = row + r |
| 12 | + next_col = col + c |
| 13 | + |
| 14 | + carrots = garden[row][col] |
| 15 | + garden[row][col] = 0 |
| 16 | + |
| 17 | + if max > 0 and next_row is not None and next_col is not None: |
| 18 | + carrots += hungry_rabbit_util(garden, next_row, next_col) |
| 19 | + |
| 20 | + return carrots |
| 21 | + |
| 22 | + |
| 23 | +def find_center(garden): |
| 24 | + row_options = [len(garden) // 2, len(garden) // 2] |
| 25 | + col_options = [len(garden[0]) // 2, len(garden[0]) // 2] |
| 26 | + |
| 27 | + # If even, 1st option is one less than half the length |
| 28 | + if len(garden) % 2 == 0: |
| 29 | + row_options[0] -= 1 |
| 30 | + |
| 31 | + if len(garden[0]) % 2 == 0: |
| 32 | + col_options[0] -= 1 |
| 33 | + |
| 34 | + max = 0 |
| 35 | + row = None |
| 36 | + col = None |
| 37 | + |
| 38 | + for r_option in row_options: |
| 39 | + for c_option in col_options: |
| 40 | + if garden[r_option][c_option] > max: |
| 41 | + max = garden[r_option][c_option] |
| 42 | + row = r_option |
| 43 | + col = c_option |
| 44 | + |
| 45 | + return row, col |
| 46 | + |
| 47 | + |
| 48 | +def hungry_rabbit(garden): |
| 49 | + if len(garden) == 0 or len(garden[0]) == 0: |
| 50 | + return 0 |
| 51 | + |
| 52 | + # create a copy of the garden so we can mutate it |
| 53 | + copy = [g_row[:] for g_row in garden] |
| 54 | + row, col = find_center(copy) |
| 55 | + |
| 56 | + if row is None or col is None: |
| 57 | + return 0 |
| 58 | + |
| 59 | + return hungry_rabbit_util(copy, row, col) |
| 60 | + |
| 61 | + |
| 62 | +if __name__ == "__main__": |
| 63 | + garden = [ |
| 64 | + [5, 7, 8, 6, 3], |
| 65 | + [0, 0, 7, 0, 4], |
| 66 | + [4, 6, 3, 4, 9], |
| 67 | + [3, 1, 0, 5, 8] |
| 68 | + ] |
| 69 | + |
| 70 | + print hungry_rabbit(garden) |
0 commit comments