Thoughts on leetcode 1368
https://leetcode.com/problems/minimum-cost-to-make-at-least-one-valid-path-in-a-grid/
We consider the cell that can be reached with no cost at the same level as the previous cell. Therefore, we maintain a two-end queue so that 0-cost cells are inserted into the front and 1-cost cells are inserted into the end. Also, we keep track of the current level size.
Pay attention that different from the previous BFS, we need to set the cell as visited after it is popped from the queue. This is because the cost of the cell can be re-evaluated (The problem is more like a simplified version of dijkstra)
template
for all v in vertices:
dist[v] = inf
dist[source] = 0;
deque d
d.push_front(source)
while d.empty() == false:
vertex = get front element and pop as in BFS.
for all edges e of form (vertex , u):
if travelling e relaxes distance to u:
relax dist[u]
if e.weight = 1:
d.push_back(u)
else:
d.push_front(u)
Solution for leetcode1368
class Solution {
public int minCost(int[][] grid) {
int m = grid.length;
int n = grid[0].length;
Deque<int[]>queue=new ArrayDeque();
int[][]directions={{0,0},{0,1},{0,-1},{1,0},{-1,0}};
boolean[][] visited = new boolean[m][n];
queue.add(new int[]{0,0});
int ans = 0;
while(queue.size() != 0){
int size = queue.size();
while(size != 0){
int[] cur = queue.pollFirst();
size--;
int curx = cur[0];
int cury = cur[1];
visited[curx][cury] = true;
if(curx == m - 1 && cury == n - 1){
return ans;
}
for(int i = 1; i < directions.length; i++){
int newx = cur[0] + directions[i][0];
int newy = cur[1] + directions[i][1];
if(newx < 0 || newx >= m || newy < 0 || newy >= n || visited[newx][newy] == true ){
continue;
}
//there is no cost to go to this cell from the last cell
// we can consider them on the same level
if(i == grid[curx][cury]){
queue.addFirst(new int[]{newx, newy});
size++;
}
else{
queue.addLast(new int[]{newx,newy});
}
}
}
ans++;
}
return 0;
}
}