Solution using C++


  • 0
    V
    class Solution {
    public:
        vector<vector<int>> dp;
        vector<vector<int>> arr;
        
        bool searchMatrix(vector<vector<int>>& matrix, int target) 
        {
            arr = matrix;
    		vector<int> row1, row2, row3, row4, row5;
            row1 = {-1, -1, -1, -1, -1};
    		row2 = {-1, -1, -1, -1, -1};
    		row3 = {-1, -1, -1, -1, -1};
    		row4 = {-1, -1, -1, -1, -1};
    		row5 = {-1, -1, -1, -1, -1};
    		dp.push_back(row1);
    		dp.push_back(row2);
    		dp.push_back(row3);
    		dp.push_back(row4);
    		dp.push_back(row5);
            return search(matrix, 0,0,target);
        }
        
        bool search(vector<vector<int>>& matrix, int i, int j, int target) 
        {
            if(matrix.size() == 0)
                return false;
            if(i>arr.size()-1 || j>arr[0].size()-1 || i<0 || j<0)
    				return false;
    			if(arr[i][j] == target)
    				return true;
    
    			if(dp[i][j] != 1)
    			{
    				dp[i][j]=1;
    				if(arr[i][j] < target)
    					return (search(matrix,i+1,j,target) || search(matrix,i,j+1,target));
    				else
    					return (search(matrix,i-1,j,target) || search(matrix,i,j-1,target));
    			}
    			return false;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.