---
# System prepended metadata

title: 2087. Minimum Cost Homecoming of a Robot in a Grid
tags: [Leetcode, Medium, Greedy]

---

# 2087. Minimum Cost Homecoming of a Robot in a Grid
###### tags: `Leetcode` `Medium` `Greedy`
Link: https://leetcode.com/problems/minimum-cost-homecoming-of-a-robot-in-a-grid/description/
## 思路
最短路径的cost一定等于从```startPos[0]```到```homePos[0]```中间所有row的cost+```startPos[1]```到```homePos[1]```中间所有col的cost
## Code
```java=
class Solution {
    public int minCost(int[] startPos, int[] homePos, int[] rowCosts, int[] colCosts) {
        int res = 0;
        int i = startPos[0], j = startPos[1];
        int x = homePos[0], y = homePos[1];
        while(i!=x){
            i += (x-i)/Math.abs(x-i);
            res += rowCosts[i];
        }
        while(j!=y){
            j += (y-j)/Math.abs(y-j);
            res += colCosts[j];
        }
        return res;
    }
}
```