Minimum Cost Homecoming of a Robot in a Grid LeetCode solution in Java

1
class Solution {
2
public int minCost(int[] startPos, int[] homePos, int[] rowCosts, int[] colCosts) {
3
int total = 0;
4

5
// if home is to the down of start move, down till there
6
if (homePos[0] > startPos[0]) {
7
int i = startPos[0] + 1;
8
while (i <= homePos[0]) {
9
total += rowCosts[i]; // adding cost while moving corresponding to the cell
10
i++;
11
}
12
}
13

14
// else if home is up from the start, move up till there
15
else if (homePos[0] < startPos[0]) {
16
int i = startPos[0] - 1;
17
while (i >= homePos[0]) {
18
total += rowCosts[i]; // adding cost while moving corresponding to the cell
19
i--;
20
}
21
}
22

23
// if home is right to the start, move right till there
24
if (homePos[1] > startPos[1]) {
25
int i = startPos[1] + 1;
26
while (i <= homePos[1]) {
27
total += colCosts[i]; // adding cost while moving corresponding to the cell
28
i++;
29
}
30
}
31

32
// else if home is left to the start, move left till there
33
else if (homePos[1] < startPos[1]) {
34
int i = startPos[1] - 1;
35
while (i >= homePos[1]) {
36
total += colCosts[i]; // adding cost while moving corresponding to the cell
37
i--;
38
}
39
}
40

41
return total;
42
}
43
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0