// if use row*width + col = the number of coordinate classSnakeGame{
/** Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0]. */ int[][] food; LinkedList<int[]> snack; HashSet<int[]> set; int n,m; int nf; publicSnakeGame(int width, int height, int[][] food){ snack = new LinkedList<>(); snack.offer(newint[]{0,0}); set = new HashSet<>(); set.add(newint[]{0,0}); this.food = food; n = height; m = width; nf = 0; } /** Moves the snake. @param direction - 'U' = Up, 'L' = Left, 'R' = Right, 'D' = Down @return The game's score after the move. Return -1 if game over. Game over when snake crosses the screen boundary or bites its body. */ publicintmove(String direction){ int[] head = newint[]{snack.peek()[0], snack.peek()[1]}; int x=head[0],y=head[1]; switch (direction){ case"U": x--; break; case"L": y--; break; case"R": y++; break; case"D": x++; break; } if (x >= n || x < 0 || y >= m || y < 0) return -1; for (int i = 1; i < snack.size()-1; i++){ if (x == snack.get(i)[0] && y == snack.get(i)[1]) return -1; } snack.addFirst(newint[]{x,y}); if (food.length > nf && x == food[nf][0] && y == food[nf][1]){ return ++nf; } snack.pollLast(); return nf; } }
/** * Your SnakeGame object will be instantiated and called as such: * SnakeGame obj = new SnakeGame(width, height, food); * int param_1 = obj.move(direction); */