My solution is timelimit exceeded, can someone please help

  • 0

    Hi, my code works in the testcases, that pass the limit of judge in my computer, and I have no idea why it is timelimit exceeded, thanks in advance

    class Solution {
        bool searchMatrix(vector<vector<int>>& matrix, int target) {
            int N= matrix.size(), M=matrix[0].size();
            return searchMatrix(matrix, target, 0,N-1, 0, M-1);    
        bool searchMatrix(vector<vector<int>>&matrix, int target, int r1, int r2, int c1, int c2) {
            if((r1>r2) || (c1>c2)) return false;
            if((r1==r2) && (c1==c2)) return (matrix[r1][c1]==target);
            int mid_r=r1+(r2-r1)/2;
            int mid_c=c1+(c2-c1)/2;
            if(matrix[mid_r][mid_c]==target) return true;
            else if(matrix[mid_r][mid_c]>target) {
                if(searchMatrix(matrix,target,r1,mid_r,c1,mid_c)) return true;
                if(searchMatrix(matrix,target,r1,mid_r,mid_c+1,c2)) return true;
                return searchMatrix(matrix,target,mid_r+1,r2,c1,mid_c);
                if(searchMatrix(matrix, target, r1, mid_r, mid_c+1, c2))         return true;
                if(searchMatrix(matrix,target,  mid_r+1,r2, c1, mid_c))        return true;
                return searchMatrix(matrix, target, mid_r+1, r2, mid_c+1, c2);

Log in to reply

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