-
Notifications
You must be signed in to change notification settings - Fork 159
Expand file tree
/
Copy pathHow many carrots can the rabbit eat.cpp
More file actions
62 lines (34 loc) · 1.04 KB
/
How many carrots can the rabbit eat.cpp
File metadata and controls
62 lines (34 loc) · 1.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/*
Given a squre, the coordinates of a rabbit and the coordinates of the carrots,
find out the number of carrots that the rabbit can eat. This is only one rabbit and all rest are carrots.
The rabbit can only eat carrots which are in its own row, own column or in any of the diagonals.
*/
/*
solution: Just scan the grid to check the row index difference, column index difference or column index difference/row index difference.
O(n^2) time, O(1) space
*/
#include<iostream>
#include<vector>
using namespace std;
int NumCarrot(int x, int y, int len) {
int result = 0;
for(int i = 0; i < len; ++i) {
for(int j = 0; j < len; ++j) {
int diffx = x - i;
int diffy = y - j;
if (diffx == 0 && diffy != 0) {
result++;
} else if (diffy == 0 && diffx != 0) {
result++;
} else if ((diffx != 0 && diffy != 0) && (diffy / diffx == 1 || diffy / diffx == -1)) {
result++;
}
}
}
return result;
}
int main() {
int len = 5;
cout<<NumCarrot(2,2, len)<<endl;
return 0;
}