看来我的想法是没问题的,就是写的太慢了,不熟练。
本题思路其实就是一个遍历问题,主要包括两步。首先找到cost相同值所对应的所有点;然后逐步往外扩展,与之相连的点为cost++的位置,直到结束。
class Solution {
public:
// judge (x, y) is ok?
bool pointok(pair<int, int>& point, int row, int col){
if (point.first>=0 && point.first<row && point.second>=0 && point.second<col){
return true;
}
else{
return false;
}
}
// return nextpoints, if not exists, then (-1, -1)
pair<int, int> newpoint(pair<int, int> point, int direction, int row, int col){
pair<int, int> temp;
if (direction==1){
temp.first = point.first;
temp.second = point.second+1;
}
else if (direction==2){
temp.first = point.first;
temp.second = point.second-1;
}
else if (direction==3){
temp.first = point.first+1;
temp.second = point.second;
}
else{ // 4
temp.first = point.first-1;
temp.second = point.second;
}
if (pointok(temp,row,col)){
return temp;
}
else{
temp.first = -1;
temp.second = -1;
return temp;
}
}
// main funcs
int minCost(vector<vector<int>>& grid) {
// save all costs => -1
int row = grid.size();
int col = grid[0].size();
if (row==1&&col==1){
return 0;
}
vector<int> temp(col, -1);
vector<vector<int>> costs(row, temp); // all -1 in costs
pair<int, int> now(0, 0);
vector<pair<int, int>> points(1, now);
vector<pair<int, int>> newpoints(1, now);
int cost = 0;
costs[0][0] = 0;
while(1){
// point = newpoints;
// newpoints = {};
points.clear();
for(int i=0;i<newpoints.size();i++){
points.push_back(newpoints[i]);
}
newpoints.clear();
// go each points, and store, add costs[][]=cost;
queue<pair<int, int>> queuepoints;
for(int i=0;i<points.size();i++){
queuepoints.push(points[i]);
}
while(!queuepoints.empty()){
pair<int, int> now = queuepoints.front();
pair<int, int> next = newpoint(now, grid[now.first][now.second], row, col);
if (next.first!=-1&&next.second!=-1&&costs[next.first][next.second]==-1){
points.push_back(next);
queuepoints.push(next);
costs[next.first][next.second] = cost;
if (next.first==row-1&&next.second==col-1){
return cost;
}
}
queuepoints.pop();
}
/*
for (int i=0;i<points.size();i++){
cout<<points[i].first<<" "<<points[i].second<<endl;
}
cout<<endl<<endl;
*/
// after update points, costs
// go sizhou, cost++;
cost ++;
for(int i=0;i<points.size();i++){
pair<int, int> now = points[i];
pair<int, int> now1(now.first-1, now.second);
pair<int, int> now2(now.first+1, now.second);
pair<int, int> now3(now.first, now.second-1);
pair<int, int> now4(now.first, now.second+1);
vector<pair<int, int>> nows;
nows.push_back(now1);
nows.push_back(now2);
nows.push_back(now3);
nows.push_back(now4);
for (int j=0;j<4;j++){
//cout<<i<<" "<<j<<endl;
pair<int, int> nowk = nows[j];
if (pointok(nowk, row, col)&&costs[nowk.first][nowk.second]==-1){ // not used
newpoints.push_back(nowk);
costs[nowk.first][nowk.second] = cost;
if (nowk.first==row-1&&nowk.second==col-1){
return cost;
}
}
}
}
/*
for (int i=0;i<newpoints.size();i++){
cout<<newpoints[i].first<<" "<<newpoints[i].second<<endl;
}
cout<<endl<<endl;*/
}
cout<<"input has error"<<endl;
return 0;
}
};