-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1368.cpp
More file actions
42 lines (41 loc) · 1.48 KB
/
1368.cpp
File metadata and controls
42 lines (41 loc) · 1.48 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
class Solution {
public:
int minCost(vector<vector<int>>& grid) {
vector<int> dirx = {0,0,1,-1};
vector<int> diry = {1,-1,0,0};
vector<int> val = {1,2,3,4};
int m = grid.size(), n = grid[0].size();
vector<vector<bool>> visited(m,vector<bool>(n,false));
vector<vector<int>> cost(m,vector<int>(n,INT_MAX));
queue<pair<int,int>> q;
q.push({0,0});
cost[0][0] = 0;
while(!q.empty()){
auto curr = q.front();
q.pop();
for(int i=0; i<4; i++){
int nr = curr.first + dirx[i];
int nc = curr.second + diry[i];
int v = val[i];
if(nr>=0 && nc>=0 && nr<m && nc<n && !visited[nr][nc]){
bool flag = false;
if(grid[curr.first][curr.second] == v){
if(cost[nr][nc]>cost[curr.first][curr.second]){
flag = true;
cost[nr][nc] = cost[curr.first][curr.second];
}
}
else{
if(cost[nr][nc]>cost[curr.first][curr.second]+1){
flag = true;
cost[nr][nc] = cost[curr.first][curr.second]+1;
}
}
if(flag)
q.push({nr,nc});
}
}
}
return cost[m-1][n-1];
}
};