注册一亩三分地论坛,查看更多干货!
您需要 登录 才可以下载或查看附件。没有帐号?注册账号
x
不明白x、y坐标为啥更新的不对,test case总是过不了。劳烦大神指正
- class SnakeGame {
- /** 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 width;
- int height;
- int[][] food;
- int foodIndex;
- Deque<int[]> queue;
- public SnakeGame(int width, int height, int[][] food) {
- this.width = width;
- this.food = food;
- foodIndex = 0;
- queue = new ArrayDeque<>();
- queue.addLast(new int[]{0, 0});
- }
-
- /** Moves the snake.
- @param direction - 'U' = Up, 'L' = Left, 'R' = Right, 'D' = Down
- [url=home.php?mod=space&uid=160137]@return[/url] The game's score after the move. Return -1 if game over.
- Game over when snake crosses the screen boundary or bites its body. */
- public int move(String direction) {
- int[] curPos = queue.peekFirst();
- int curX = curPos[0];
- int curY = curPos[1];
-
- if (direction.equals("U")) {
- --curX;
- } else if (direction.equals("D")) {
- ++curX;
- } else if (direction.equals("L")) {
- --curY;
- } else if (direction.equals("R")) {
- ++curY;
- }
-
- if (outOfRange(curX, curY) || isTouchBody(curX, curY)) {
- return -1;
- } else if (foodIndex < food.length && curX == food[foodIndex][0] && curY == food[foodIndex][1]) {
- foodIndex++;
- queue.addFirst(new int[]{curX, curY}); //头部增长
- } else {
- queue.removeLast();
- queue.addFirst(new int[]{curX, curY});//单纯前进
- }
- return queue.size() - 1;
- }
-
- boolean outOfRange (int x, int y) {
- return x < 0 || x >= height || y < 0 || y >= width;
- }
-
- boolean isTouchBody (int x, int y) {
- for (int[] pos : queue) {
- if (x == pos[0] && y == pos[1]) {
- if (x != queue.peekLast()[0] || y != queue.peekLast()[1]) {
- return true;
- }
- }
- }
- return false;
- }
- }
复制代码
补充内容 (2020-9-22 12:23):
搞清楚哪错了,constructor里没传height…… |