Help Needed || Rotten Oranges Question

I have done this question using the dfs(Flood Fill).
please help me , I want to know why this logic is wrong and can u tell we by what way i can do some required changes in this code(LOGIC) to get it accepted.
I have attached the link below of this quesition and commenteed down the code to help you understand my logic
https://leetcode.com/problems/rotting-oranges/

class Solution {
public:
    bool visited[11][11];
    int sum , ans;
    int n , m;
   
    // to check i f current cell is valid or not , i.e. the cell should be inside the grid 
	//and it must be unvisited and the cell should not be empty
    bool safe(vector<vector<int>> &grid , int i , int j){
        if(i < n && i>=0 && j < m && j>=0 && !visited[i][j] && grid[i][j]!=0 )
            return true;
        
        return false;
    }
    
    void solve(vector<vector<int>> &grid , int i , int j , int c){
       
        
        if(!safe(grid , i , j))
            return ;
			// if we are starting from the very 1st cell having value 2 
			//then we will continue with it else if the value is 2 and c!=0
			//then we will return
         if(grid[i][j] == 2 && c!=0)
            return;
       
	   // we mark the current cell as visited 
	   // and changed its value to 2 as it is rotten now
        visited[i][j] = true;
        grid[i][j] = 2;
     
	 // for every minute we are checking if its the maximum till now
        ans = max(ans , c);
        
		// checking in every 4 directions possible
        solve(grid , i+1 , j , c+1);
        solve(grid , i-1 , j , c+1);
        solve(grid , i , j+1 , c+1);
        solve(grid , i , j-1 , c+1);
        
    }
    
    int orangesRotting(vector<vector<int>>& grid) {
         n = grid.size();
         m = grid[0].size();    

        
        for(int i = 0 ; i < n; i++){
            for(int j = 0 ;j < m ; j++){
                if(!visited[i][j] && grid[i][j] == 2){
                    ans = 0 ;
                    solve(grid , i , j , 0);
                    sum+=ans;// after every call we are adding the ans 
					//into sum which will be our final ans
            }
        }
        
		// if any cell remains unrotten than we will return -1
      for(int i = 0 ; i < n ;i++){
          for(int j = 0 ; j < m ;j++)
              if(grid[i][j] == 1)
                  return -1;
            }
           
            return sum;
    
    }
};
Comments (1)