## Google Interview Question

SDE1s**Country:**United States

Easy DP could be O(n*m*(n+m)).

Greedy algorithm is iteratively choosing minimum from rest values, then check if it is valid in previous selected path by comparing its coordinate with previous coordinate and next coordinate in path. O(n*m*log(n+m))

```
struct Node{
int val;
int x;
int y;
};
int cmp(Node &a, Node &b){
return a.val < b.val;
}
vector<int> get_ans(vector<vector<int>> &grid){
int n = grid.size();
int m = grid[0].size();
vector<Node> vec(n * m - 2);
int site = 0;
for (int i = 0; i < n; ++i){
for (int j = 0; j < m; ++j){
if ((i == 0 && j == 0) || (i == n-1 && j == m-1)){
continue;
}
vec[site].val = grid[i][j];
vec[site].x = i;
vec[site].y = j;
++site;
}
}
sort(vec.begin(), vec.end(), cmp);
map<pair<int,int>, int> mp;
mp[make_pair(0,0)] = grid[0][0];
mp[make_pair(n-1,m-1)] = grid[n-1][m-1];
for (int i = 0; i < vec.size(); ++i){
pair<int, int> p = make_pair(vec[i].x, vec[i].y);
cout << p.first << ", " << p.second << endl;
auto it = mp.upper_bound(p);
if (it != mp.end() && (vec[i].x > it->first.first || vec[i].y > it->first.second)){
continue;
}
--it;
if (it != mp.end() && (vec[i].x < it->first.first || vec[i].y < it->first.second)){
continue;
}
cout << "pass" << endl;
mp[p] = vec[i].val;
}
vector<int> ans;
for (auto it = mp.begin(); it != mp.end(); ++it){
ans.push_back(it->second);
}
sort(ans.begin(), ans.end());
return ans;
}
```

Sort n+m list and keep their [i,j] as auxililary info. pick from the smallest number among the sorted n+m number list. Each consecutive pick must satisfy (i <= i_prev && j <= j_prev) || (i >= i_prev && j >= j_prev).

- Aaron December 27, 2017