First time posting here as a rookie, and welcome to comment!


  • 1

    It's naive but works OK.For a given direction, we can get the position of next move. We check if this position is beyond boundary, or has food on it, or it's just normal spot.

    public class SnakeGame{
    int[][] food;
    int width;
    int height;
    int index;
    Deque<String> q;
    public static final HashMap<String,int[]> map=new HashMap<String,int[]>(){
    	{
    		put("U",new int[]{-1,0});
    		put("D",new int[]{1,0});
    		put("L",new int[]{0,-1});
    		put("R",new int[]{0,1});
    	}
    };
    public SnakeGame(int width,int height,int[][] food){
    	this.food=food;
        this.width=width;
    	this.height=height;
    	int index;
    	q=new LinkedList<>();
    	q.offer(new String("0 0"));
    }
    
    public int move(String direction){
    	String[] curr=q.peekLast().split(" ");
    	int[] dir=map.get(direction);
        //based on the direction given, we derive next move
        int x=Integer.parseInt(curr[0])+dir[0];
    	int y=Integer.parseInt(curr[1])+dir[1];
    
    	//if next move will go beyond the boundary, or cross snake's body
    	if(x<0||x>height-1||y<0||y>width-1||q.contains(x+" "+y)&&!q.peek().equals(x+" "+y)){
    		return -1;
    	}
        
        //if there's food on the next move, then this position will become part of the snake body
    	if(index<food.length){
    		int xFood=food[index][0];
    		int yFood=food[index][1];
    		if(x==xFood&&y==yFood){
    			q.offer(x+" "+y);
    			index++;
    			return index;
    		}
    	}
        
        //normal move:neither we go cross boundary,nor we get food on the next move;we just move the   snake one step forward
    	q.offer(x+" "+y);
    	q.poll();
    	return index;
    }
    

    }


Log in to reply
 

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