My Java Solution, beat 100%


  • 0
    F

    public class SnakeGame {

    private int len = 0;
    private List<Integer> snake = new ArrayList<>();
    private int[][] food;
    private int n, m;
    private int index = 0;
    
    public SnakeGame(int width, int height, int[][] food) {
    	this.m = height;
    	this.n = width;
    	this.food = food;
    	snake.add(index);
    }
    
    public int move(String direction) {
    	int x = index / n;
    	int y = index % n;
    	switch (direction) {
    	case "U":
    		x--;
    		break;
    	case "D":
    		x++;
    		break;
    	case "L":
    		y--;
    		break;
    	case "R":
    		y++;
    		break;
    	}
    	if (len< food.length && x == food[len][0] && y == food[len][1]) {
    		len++;
    	} else
    		snake.remove(snake.size() - 1);
    	
    	if (x < 0 || x >= m || y < 0 || y >= n || snake.contains(x * n + y)) {
    		return -1;
    	}
    	index = x * n + y;
    	snake.add(0, index);
    	
    	return len;
    }
    

    }


Log in to reply
 

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