Thursday, August 11, 2016
LeetCode [353] Design Snake Game
Given width = 3, height = 2, and food = [[1,2],[0,1]].
Snake snake = new Snake(width, height, food);
Initially the snake appears at position (0,0) and the food at (1,2).
|S| | |
| | |F|
snake.move("R"); -> Returns 0
| |S| |
| | |F|
snake.move("D"); -> Returns 0
| | | |
| |S|F|
snake.move("R"); -> Returns 1 (Snake eats the first food and right after that, the second food appears at (0,1) )
| |F| |
| |S|S|
snake.move("U"); -> Returns 1
| |F|S|
| | |S|
snake.move("L"); -> Returns 2 (Snake eats the second food)
| |S|S|
| | |S|
snake.move("U"); -> Returns -1 (Game over because snake collides with border)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 | class SnakeGame { set<pair<int, int>> hist; //keep the coordinates of the current snake. used to decide if the snake eats itself deque<pair<int, int>> snake; //also keep the snake coordinates. used to update the snake body after each movement vector<vector<int>> food; int pos; //store the food position int w, h; public: /** 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]. */ SnakeGame(int width, int height, vector<vector<int>> &food) { w = width; h = height; pos = 0; this->food = food; pair<int, int> p = make_pair(0, 0); snake.push_front(p); hist.insert(p); } /** 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. */ int move(string direction) { pair<int, int> tail = snake.back(); pair<int, int> head = snake.front(); //remove the tail snake.pop_back(); hist.erase(tail); if (direction == "U") head.first--; if (direction == "L") head.second--; if (direction == "R") head.second++; if (direction == "D") head.first++; //game over if (head.first < 0 || head.first >= h || head.second < 0 || head.second >= w || hist.count(head)) return -1; //add new head snake.push_front(head); hist.insert(head); //no more food. score is the snake size minus the original size 1 if (pos == food.size()) return snake.size() - 1; //extend the snake body by adding the tail back if (head.first == food[pos][0] && head.second == food[pos][1]) { snake.push_back(tail); hist.insert(tail); pos++; } return snake.size() - 1; } }; /** * Your SnakeGame object will be instantiated and called as such: * SnakeGame* obj = new SnakeGame(width, height, food); * int param_1 = obj->move(direction); */ |
class SnakeGame { int foodIndex = 0; Set<Integer> hist = new HashSet<>(); Deque<Integer> body = new LinkedList<>(); int w, h; int[][] food; /** 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]. */ public SnakeGame(int width, int height, int[][] food) { w = width; h = height; this.food = food; body.add(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. */ public int move(String direction) { int head = body.peekFirst(); int tail = body.peekLast(); //remove tail body.removeLast(); hist.remove(tail); int i = head/w, j = head%w; if(direction.equals("U")) i--; if(direction.equals("D")) i++; if(direction.equals("L")) j--; if(direction.equals("R")) j++; int newPostion = i*w+j; //game over if(i<0 || i>=h || j<0 || j>=w || hist.contains(newPostion)) return -1; //add new head body.addFirst(newPostion); hist.add(newPostion); //no more food, score is body size -1 if(foodIndex == food.length) return body.size()-1; //eat food, body length increases by 1 to the end if(i==food[foodIndex][0] && j==food[foodIndex][1]){ body.add(tail); hist.add(tail); foodIndex++; } return body.size()-1; } } /** * Your SnakeGame object will be instantiated and called as such: * SnakeGame obj = new SnakeGame(width, height, food); * int param_1 = obj.move(direction); */
LeetCode [351] Android Unlock Patterns
351. Android Unlock Patterns
Given an Android 3x3 key lock screen and two integers m and n, where 1 ≤ m ≤ n ≤ 9, count the total number of unlock patterns of the Android lock screen, which consist of minimum of m keys and maximum n keys.
Rules for a valid pattern:
- Each pattern must connect at least m keys and at most n keys.
- All the keys must be distinct.
- If the line connecting two consecutive keys in the pattern passes through any other keys, the other keys must have previously selected in the pattern. No jumps through non selected key is allowed.
- The order of keys used matters.
Explanation:
| 1 | 2 | 3 | | 4 | 5 | 6 | | 7 | 8 | 9 |
Invalid move: 4 - 1 - 3 - 6
Line 1 - 3 passes through key 2 which had not been selected in the pattern.
Invalid move: 4 - 1 - 9 - 2
Line 1 - 9 passes through key 5 which had not been selected in the pattern.
Valid move: 2 - 4 - 1 - 3 - 6
Line 1 - 3 is valid because it passes through key 2, which had been selected in the pattern
Valid move: 6 - 5 - 4 - 1 - 9 - 2
Line 1 - 9 is valid because it passes through key 5, which had been selected in the pattern.
Example:
Input: m = 1, n = 1 Output: 9
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | public class Solution { // cur: the current position // remain: the steps remaining int DFS(boolean vis[], int[][] skip, int cur, int remain) { if(remain < 0) return 0; if(remain == 0) return 1; vis[cur] = true; int rst = 0; for(int i = 1; i <= 9; ++i) { // If vis[i] is not visited and (two numbers are adjacent or skip number is already visited) if(!vis[i] && (skip[cur][i] == 0 || (vis[skip[cur][i]]))) { rst += DFS(vis, skip, i, remain - 1); } } vis[cur] = false; return rst; } public int numberOfPatterns(int m, int n) { // Skip array represents number to skip between two pairs int skip[][] = new int[10][10]; skip[1][3] = skip[3][1] = 2; skip[1][7] = skip[7][1] = 4; skip[3][9] = skip[9][3] = 6; skip[7][9] = skip[9][7] = 8; skip[1][9] = skip[9][1] = skip[2][8] = skip[8][2] = skip[3][7] = skip[7][3] = skip[4][6] = skip[6][4] = 5; boolean vis[] = new boolean[10]; int rst = 0; // DFS search each length from m to n for(int i = m; i <= n; ++i) { rst += DFS(vis, skip, 1, i - 1) * 4; // 1, 3, 7, 9 are symmetric rst += DFS(vis, skip, 2, i - 1) * 4; // 2, 4, 6, 8 are symmetric rst += DFS(vis, skip, 5, i - 1); // 5 } return rst; } } |
Monday, July 25, 2016
LeetCode [350] Intersection of Two Arrays II
Given two arrays, write a function to compute their intersection.
Example 1:
Input: nums1 = [1,2,2,1], nums2 = [2,2] Output: [2,2]
Example 2:
Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4] Output: [4,9]
Note:
- Each element in the result should appear as many times as it shows in both arrays.
- The result can be in any order.
Follow up:
- What if the given array is already sorted? How would you optimize your algorithm?
- What if nums1's size is small compared to nums2's size? Which algorithm is better?
- What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | class Solution { public: vector<int> intersect(vector<int>& nums1, vector<int>& nums2) { unordered_map<int, int> mp;//number, count for(auto n:nums1) mp[n]++; vector<int> ret; for(auto n:nums2){ if(mp.count(n) && mp[n]>0){ mp[n]--; ret.push_back(n); } } return ret; } }; |
LeetCode [349] Intersection of Two Arrays
Input: nums1 = [1,2,2,1], nums2 = [2,2] Output: [2]
Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4] Output: [9,4]
- Each element in the result must be unique.
- The result can be in any order.
1 2 3 4 5 6 7 8 9 10 11 12 | class Solution { public: vector<int> intersection(vector<int>& nums1, vector<int>& nums2) { set<int> st(nums1.begin(), nums1.end()); set<int> st1; for(auto n:nums2){ if(st.count(n)) st1.insert(n); } vector<int> ret(st1.begin(), st1.end()); return ret; } }; |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | class Solution { public: vector<int> intersection(vector<int>& nums1, vector<int>& nums2) { sort(nums1.begin(), nums1.end()); sort(nums2.begin(), nums2.end()); vector<int> ret; int i=0, j = 0, n1 = nums1.size(), n2 = nums2.size(); while(i<n1 && j<n2){ if(nums1[i]<nums2[j]) i++; else if(nums1[i]>nums2[j]) j++; else{ if(ret.empty() || ret.back()!=nums1[i]){ ret.push_back(nums1[i]); } i++; j++; } } return ret; } }; |
