Below is my code for LEETCODE PROBLEM https://leetcode.com/problems/where-will-the-ball-fall/solutions/ :
My approach is to create a map to store the initial positions of each ball in each respective column. Then I check whether the ball can go down the matrix by checking with the appropriate neighbor. If the ball can't go down I delete it from the map and in the end print the result for which the entries are present in the map, else -1.
The code's logic is working perfectly for all the test cases but on a later test case(input as [[-1,1,-1,-1,-1,-1,-1,-1,1,-1,-1,-1,-1,1,1,-1,-1,-1,1,1,1,-1,-1,1,1,-1,-1,1,-1,-1,-1,-1,-1,-1,-1,-1,-1,1,-1,1,-1,-1,-1,-1,-1,-1,-1,1,-1,-1,1,-1,1,-1,-1,1,1,-1,1,-1,-1,-1,-1,1,1,1,1,1,1,-1,1,1,1,-1,1,1,1,-1,-1,-1,1,-1,1,-1,-1,1,1,-1,-1,1,-1,1,-1,1,1,1,-1,-1,-1,-1]]
from the server).
The code stops working after key=14. What happens is it firsts find appropriate result for key=13, then deletes key=14 as it does not go down. But instead of going to next key which is 15 it goes back to 13 and terminates.
NOTE: The problem is not that it terminates, but it goes back to 13 instead of 15.
Please help me! Thanks in advance...
class Solution {
public:
void display_map(map<int, pair<int, int>> m){
for(auto i = m.begin(); i != m.end(); i++){
cout << i->first << " " << i->second.first << " " << i->second.second << endl;
}
}
bool check_neigh(int state, vector<vector<int>> grid, int i, int j){
int new_i, new_j = j + state;
if(new_j < 0 || new_j == grid[i].size()) return false;
if(state == grid[i][new_j]) return true;
return false;
}
vector<int> findBall(vector<vector<int>>& grid) {
vector<int> answer;
map<int, pair<int, int>> Balls;
for(int i=0; i < grid[0].size(); i++){
Balls[i].first = 0;
Balls[i].second = i;
}
// display_map(Balls);
// cout << endl;
bool flag1 = true;
bool flag2 = true;
int level = 0;
while(Balls.size() != 0 && flag1){
cout << "--------------------Next Cycle--------------------\n";
auto i = Balls.begin();
for(; i != Balls.end(); i++){
cout << "Beginning: " << Balls.begin()->first << endl;
int key = i->first;
int m = i->second.first;
int n = i->second.second;
// if(m > level) continue;
cout << "key: "<<i->first << " m: " << m << " n: " << n << endl;
if(m >= grid.size()){
flag2 = false;
break;
}
int state = grid[m][n];
bool stat = check_neigh(state, grid, m, n);
if(stat == true){
i->second.first += 1;
i->second.second += state;
cout << "New key: "<<i->first << " m: " << i->second.first << " n: " << i->second.second << endl;
}
else if(stat == false){
cout << "Deleted key: "<< i->first << endl;
Balls.erase(i);
}
// level++;
display_map(Balls);
}
// for(auto i = Balls.begin(); i != Balls.end(); i++){
// if(i->second.first == level){
// Balls.erase(i);
// }
// }
// level++;
display_map(Balls);
if(flag2 == false){
flag1 = false;
}
}
for(int i = 0; i < grid[0].size(); i++){
if(Balls.find(i) != Balls.end()){
answer.push_back(Balls[i].second);
}
else{
answer.push_back(-1);
}
}
return answer;
}
};