Java solution that works


  • 0
    S
    class Solution {
        public boolean isSelfCrossing(int[] x) {
            List<Point> route = new ArrayList<Point>();
            boolean selfCrossing = false;
            route.add(new Point(0,0));
            int xFactor = 1;
            int yFactor = -1;
            for (int i=0; i<x.length; i++) {
              if(i%2==0){
                yFactor*=-1;
                selfCrossing = addToRoute(route, 0, x[i] * yFactor);
              } else {
                xFactor*=-1;
                selfCrossing = addToRoute(route, x[i] * xFactor, 0);
              }
              
              if(selfCrossing) {
                return true;
              }
            }
          return selfCrossing;
        }
        public boolean addToRoute(List<Point> route, int x, int y) {
          Point currPos = route.get(route.size()-1);
          if(x==0) {
            if(y>0) {
              for (int i=currPos.y+1; i<=currPos.y + y; i++) {
                if(addRoutes(route, currPos.x, i)) return true;
              } 
            } else {
              for (int i=currPos.y-1; i>=currPos.y+y; i--) {
                if(addRoutes(route, currPos.x, i)) return true;
              }
            }
          } else {
            if(x>0) {
              for (int i=currPos.x+1; i<=currPos.x+x; i++) {
                if(addRoutes(route, i, currPos.y)) return true;
              } 
            } else {
              for (int i=currPos.x-1; i>=currPos.x+x; i--) {
                if(addRoutes(route, i, currPos.y)) return true;
              }
            }
          }
          return false;
        }
      
      public boolean addRoutes(List<Point> route, int currX, int currY) {
        Point tmp = null;
        tmp = new Point(currX, currY);
        if(route.contains(tmp)) return true;
        route.add(tmp);
        return false;
      }
      
    }
    
    class Point {
      int x;
      int y;
      Point(int x, int y) {
        this.x = x;
        this.y = y;
      }
      @Override
      public boolean equals(Object o) {
        if(o == this) return true;
        if(!(o instanceof Point)) return false;
        Point obj = (Point) o;
        return (Integer.compare(obj.x, x)==0 && Integer.compare(obj.y, y)==0);
      }
       @Override
        public String toString() {
            return String.format("(" + x + "," + y + ")");
        }
    }
    

Log in to reply
 

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