class Solution {
public:
int swimInWater(vector<vector<int>>& grid) {
//DFS
int w, h;
h = grid.size();
w = grid[0].size();
vector<vector<bool>> visit;
for (int i = 0; i < h; i++) {
vector<bool> tmp(w, false);
visit.push_back(tmp);
}
typedef pair<int, pair<int,int>> item;
std::priority_queue<item, vector<item>, std::greater<item>> q;
item t = (make_pair(grid[0][0], make_pair(0, 0)));
visit[0][0] = true;
q.push(t);
while(1) {
int x, y;
int max = 0;
item now = q.top(); q.pop();
y = now.second.first; x = now.second.second;
if (y > 0 && !visit[y - 1][x]) {
int max = grid[y - 1][x] > now.first ? grid[y - 1][x] : now.first ;
q.push(make_pair(max, make_pair(y - 1, x)));
visit[y - 1][x] = true;
}
if (x > 0 && !visit[y][x - 1]) {
int max = grid[y][x - 1] > now.first ? grid[y][x - 1] : now.first ;
q.push(make_pair(max, make_pair(y, x - 1)));
visit[y][x - 1] = true;
}
if (y < h - 1 && !visit[y + 1][x]) {
int max = grid[y + 1][x] > now.first ? grid[y + 1][x] : now.first ;
if ((y + 1 == h - 1) && (x == w - 1)) {
cout << "OK" << endl;
return max;
}
q.push(make_pair(max, make_pair(y + 1, x)));
visit[y + 1][x] = true;
}
if (x < w - 1 && !visit[y][x + 1]) {
int max = grid[y][x + 1] > now.first ? grid[y][x + 1] : now.first ;
if ((y== h - 1) && (x + 1 == w - 1)) {
cout << "OK" << endl;
return max;
}
q.push(make_pair(max, make_pair(y, x + 1)));
visit[y][x + 1] = true;
}
}
}
};
留言
張貼留言