My java solution got a Time Limit Exceeded ,could you help me ?


  • 0
    S

    public boolean doExist(char[][] chs, char[] target, int x, int y,
    int len, boolean [][] used){

    	if (x >= chs.length || y >= chs[0].length || y < 0 || x < 0) {
    		return false;
    	}
    
    	if (!used[x][y] && len == target.length - 1 && target[len] == chs[x][y] ){				
    		return true; 
    	}
    	
    	    boolean foward = false;
    	    boolean backward = false;
    	    boolean up = false;
    	    boolean down = false;
    	    
    	  		    
    		if (!used[x][y]) {	
    			used[x][y] = true;
    			if (chs[x][y] != target[len]){			
    				foward = doExist(chs, target, x, y + 1, len ,used);	
    				backward = doExist(chs, target, x, y - 1, len,used);						
    				down = doExist(chs, target, x + 1, y, len,  used);
    				up = doExist(chs, target, x - 1, y, len,  used);
    				
    			}else{							
    				foward = doExist(chs, target, x, y + 1, len + 1,used);	
    				backward = doExist(chs, target, x, y - 1, len + 1,used);
    			
    				down = doExist(chs, target, x + 1, y, len + 1, used);
    				up = doExist(chs, target, x - 1, y, len + 1, used);
    				
    			}	
    			used[x][y]= false;	
    		} 
    		
    	return (foward |down|backward|up);
    	
    }

Log in to reply
 

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