My plain Java solution, slow but very easy to understand


  • 0
    L
    public boolean isSelfCrossing(int[] x) {
        	        List<int[]> all = new ArrayList<int[]> ();
        	        
        	        int[] prev = {0, 0};
        	        for (int i = 0; i < x.length; i++) {
        	        	int mod = i % 4;
        	        	int[] line = new int[4];
        	        	line[0] = prev[0];
        	        	line[1] = prev[1];
        	        	switch( mod) {
        	        	case 0:
        	        		prev[1] -= x[i];
        	        		break;
        	        	case 1: 
        	        		prev[0] -= x[i];
        	        		break;
        	        	case 2:
        	        		prev[1] += x[i];
        	        		break;
        	        	case 3: 
        	        		prev[0] += x[i];
        	        		break;    	        	
        	        	}
        	        	
        	        	line[2] = prev[0];
        	        	line[3] = prev[1];
        	        	
        	        	if (i > 2) {
        	        		for (int j = all.size() -3;  j >= 0; j -= 1) {
        	        			if (isCrossing(line, all.get(j))) return true;
        	        		}
        	        	}
        	        	all.add(line);
        	        }
        	        
        	        return false;
        	    }
        	    
        	    boolean isCrossing(int[] line1, int[] line2) {
        	    	int[] v = (line1[0] == line1[2]) ? line1 : line2;
        	    	int[] h = (v == line1) ? line2 : line1;
        	    	
        	    	return ((v[0] >= h[0] && v[0] <= h[2]) || (v[0] >= h[2] && v[0] <= h[0])) && ((h[1] >= v[1] && h[1] <= v[3]) || (h[1] >= v[3] && h[1] <= v[1]));
        	    }
    

Log in to reply
 

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