LeetCode 723 - Candy Crush


http://bookshadow.com/weblog/2017/11/05/leetcode-candy-crush/
This question is about implementing a basic elimination algorithm for Candy Crush.
Given a 2D integer array board representing the grid of candy, different positive integers board[i][j]represent different types of candies. A value of board[i][j] = 0 represents that the cell at position (i, j) is empty. The given board represents the state of the game following the player's move. Now, you need to restore the board to a stable state by crushing candies according to the following rules:
  1. If three or more candies of the same type are adjacent vertically or horizontally, "crush" them all at the same time - these positions become empty.
  2. After crushing all candies simultaneously, if an empty space on the board has candies on top of itself, then these candies will drop until they hit a candy or bottom at the same time. (No new candies will drop outside the top boundary.)
  3. After the above steps, there may exist more candies that can be crushed. If so, you need to repeat the above steps.
  4. If there does not exist more candies that can be crushed (ie. the board is stable), then return the current board.
You need to perform the above rules until the board becomes stable, then return the current board.
Example 1:
Input:
board = 
[[110,5,112,113,114],[210,211,5,213,214],[310,311,3,313,314],[410,411,412,5,414],[5,1,512,3,3],[610,4,1,613,614],[710,1,2,713,714],[810,1,2,1,1],[1,2,1,2,2],[4,1,4,4,1014]]
Output:
[[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[110,0,0,0,114],[210,0,0,0,214],[310,0,0,113,314],[410,0,0,213,414],[610,211,112,313,614],[710,311,412,613,714],[810,411,512,713,1014]]
Explanation: 

Note:
  1. The length of board will be in the range [3, 50].
  2. The length of board[i] will be in the range [3, 50].
  3. Each board[i][j] will initially start as an integer in the range [1, 2000].
模拟实现游戏“糖果粉碎传奇”
给定二维数组board,每行、列中3个或以上连续相同的数字都可以被消去(变为0表示空位),消去后位于上方的数字会填充空位。
重复直到没有更多的数字可以被消去。
https://blog.csdn.net/magicbean2/article/details/79331607
这道题目本身并不难,算法框架分为两步:1)标记出所有需要被crash掉的元素;2)将这些元素置为0,并且crash。但是我感觉难的地方是如何确定哪些元素需要被crash。例如在题目中给出的例子中,5个“2”需要被crash,但是只有4个“1”需要被crash,而board[8][0]位置上的1不可以被crash(这也是我开始写的程序怎么都跑不对的原因)。为了解决这一问题,我的思路是:如果一个元素可以被crash,则我们首先将其置为负数。这样在判断某个元素是否可以被crash的时候,我们就判断它的纵向或者横向是否存在三个连续的位置,其值不为0,并且绝对值相同。如果可以被crash,则将其置为原数对应的负数。这样在后面crash的时候,我们只需要保留正数,而将所有的非正数都置为0。


模拟题
循环,把拟被消去的数字替换为其相反数,遍历每一列,自底向上遍历每一行,将负数消去。
当某一次消去未找到任何数字时,循环终止。
https://github.com/joy32812/leetcode/blob/master/src/com/leetcode/P723_CandyCrush.java
  int m, n;
  int[][] B;

  public int[][] candyCrush(int[][] board) {

    B = board;
    m = B.length;
    n = B[0].length;

    while (crash()) {
      drop();
    }

    for (int i = 0; i < m; i++) {
      for (int j = 0; j < n; j++) {
        System.out.print(B[i][j] + " ");
      }
      System.out.println();
    }
    return B;
  }

  private boolean crash() {

    boolean[][] c = new boolean[m][n];
    for (int i = 0; i < m; i++) {
      for (int j = 0; j < n; j++) {
        if (B[i][j] == 0)
          continue;

        int cnt = 1;
        // right
        for (int k = j + 1; k < n; k++) {
          if (B[i][k] == B[i][j])
            cnt++;
          else
            break;
        }

        if (cnt >= 3) {
          for (int k = j; k < n && k < j + cnt; k++) {
            c[i][k] = true;
          }
        }

        // down
        cnt = 1;
        for (int k = i + 1; k < m; k++) {
          if (B[i][j] == B[k][j])
            cnt++;
          else
            break;
        }

        if (cnt >= 3) {
          for (int k = i; k < m && k < i + cnt; k++) {
            c[k][j] = true;
          }
        }
      }
    }

    boolean crash = false;
    for (int i = 0; i < m; i++) {
      for (int j = 0; j < n; j++) {
        if (c[i][j]) {
          crash = true;
          B[i][j] = 0;
        }
      }
    }

    return crash;
  }

  private void drop() {
    for (int j = 0; j < n; j++) {

      int now = m - 1;
      for (int i = m - 1; i >= 0; i--) {
        if (B[i][j] == 0)
          continue;
        int tp = B[i][j];
        B[i][j] = B[now][j];
        B[now][j] = tp;
        now--;
      }

    }

  }
http://www.cnblogs.com/grandyang/p/7858414.html
这道题就是糖果消消乐,博主刚开始做的时候,没有看清楚题意,以为就像游戏中的那样,每次只能点击一个地方,然后消除后糖果落下,这样会导致一个问题,就是原本其他可以消除的地方在糖果落下后可能就没有了,所以博主在想点击的顺序肯定会影响最终的stable的状态,可是题目怎么没有要求返回所剩糖果最少的状态?后来发现,其实这道题一次消除table中所有可消除的糖果,然后才下落,形成新的table,这样消除后得到的结果就是统一的了,这样也大大的降低了难度。下面就来看如何找到要消除的糖果,可能有人会想像之前的岛屿的题目一样找连通区域,可是这道题的有限制条件,只有横向或竖向相同的糖果数达到三个才能消除,并不是所有的连通区域都能消除,所以找连通区域不是一个好办法。最好的办法其实是每个糖果单独检查其是否能被消除,然后把所有能被删除的糖果都标记出来统一删除,然后在下落糖果,然后再次查找,直到无法找出能够消除的糖果时达到稳定状态。好,那么我们用一个数组来保存可以被消除的糖果的位置坐标,判断某个位置上的糖果能否被消除的方法就是检查其横向和纵向的最大相同糖果的个数,只要有一个方向达到三个了,当前糖果就可以被消除。所以我们对当前糖果的上下左右四个方向进行查看,用四个变量x0, x1, y0, y1,其中x0表示上方相同的糖果的最大位置,x1表示下方相同糖果的最大位置,y0表示左边相同糖果的最大位置,y1表示右边相同糖果的最大位置,均初始化为当前糖果的位置,然后使用while循环向每个方向遍历,注意我们并不需要遍历到头,而是只要遍历三个糖果就行了,因为一旦查到了三个相同的,就说明当前的糖果已经可以消除了,没必要再往下查了。查的过程还要注意处理越界情况,好,我们得到了上下左右的最大的位置,分别让相同方向的做差,如果水平和竖直方向任意一个大于3了,就说明可以消除,将坐标加入数组del中。注意这里一定要大于3,是因为当发现不相等退出while循环时,坐标值已经改变了,所以已经多加了或者减了一个,所以差值要大于3。遍历完成后,如果数组del为空,说明已经stable了,直接break掉,否则将要消除的糖果位置都标记为0,然后进行下落处理。下落处理实际上是把数组中的0都移动到开头,那么就从数组的末尾开始遍历,用一个变量t先指向末尾,然后然后当遇到非0的数,就将其和t位置上的数置换,然后t自减1,这样t一路减下来都是非0的数,而0都被置换到数组开头了
    vector<vector<int>> candyCrush(vector<vector<int>>& board) {
        int m = board.size(), n = board[0].size();
        while (true) {
            vector<pair<int, int>> del;
            for (int i = 0; i < m; ++i) {
                for (int j = 0; j < n; ++j) {
                    if (board[i][j] == 0) continue;
                    int x0 = i, x1 = i, y0 = j, y1 = j;
                    while (x0 >= 0 && x0 > i - 3 && board[x0][j] == board[i][j]) --x0;
                    while (x1 < m && x1 < i + 3 && board[x1][j] == board[i][j]) ++x1;
                    while (y0 >= 0 && y0 > j - 3 && board[i][y0] == board[i][j]) --y0;
                    while (y1 < n && y1 < j + 3 && board[i][y1] == board[i][j]) ++y1;
                    if (x1 - x0 > 3 || y1 - y0 > 3) del.push_back({i, j});
                }
            }
            if (del.empty()) break;
            for (auto a : del) board[a.first][a.second] = 0;
            for (int j = 0; j < n; ++j) {
                int t = m - 1;
                for (int i = m - 1; i >= 0; --i) {
                    if (board[i][j]) swap(board[t--][j], board[i][j]);   
                }
            }
        }
        return board;
    }
https://www.codetd.com/article/154114
画图模拟比较好理解.
vector<vector<int>> candyCrush(vector<vector<int>>& board) { int m = board.size(); int n = board[0].size(); while (true) { vector<pair<int, int>> to_crash; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (board[i][j]) { //为了减小计算量,元素为0的略过 int i1 = i, i0 = i, j1 = j, j0 = j; // i1,i0,j1,j0分别为向下,向上,向右,向左的检测 //对每个点(i,j),以其为中心,向上下或左右方向扩展,看是否有连续 while (i1 < m && i1 < i+3 && board[i1][j] == board[i][j]) i1++; while (i0 >= 0 && i0 > i-3 && board[i0][j] == board[i][j]) i0--; while (j1 < n && j1 < j+3 && board[i][j1] == board[i][j]) j1++; while (j0 >= 0 && j0 > j-3 && board[i][j0] == board[i][j]) j0--; if (i1-i0 > 3 || j1-j0 > 3) to_crash.push_back({i,j}); //上下或左右连续元素超过3,即符合 } } } if (to_crash.empty()) break; for (auto t : to_crash) board[t.first][t.second] = 0; //重点:将所有标记位置置0 for (int j = 0; j < n; j++) { //由于是自上往下消除,因此外层对j(纵坐标)循环 int t = m-1; //t用于记录新board的横坐标 for (int i = m-1; i >= 0; i--) { //从下往上,非0元素参与交换,每次交换后t上移 if (board[i][j]) swap(board[i][j], board[t--][j]); } } } return board; }
https://www.cnblogs.com/jxr041100/p/8440349.html
public int[][] candyCrush(int[][] board) {
        if (board == null || board.length == 0 || board[0].length == 0) return board;
        int cnt = 0;
        int m = board.length, n = board[0].length;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (board[i][j] == 0) continue;
                if (   (i > 0 && Math.abs(board[i-1][j]) == board[i][j] && (i < m - 1 && board[i+1][j] == board[i][j]))
                    || (i > 1 && Math.abs(board[i-1][j]) == board[i][j] && Math.abs(board[i-2][j]) == board[i][j])
                    || (i < m - 2 && board[i+1][j] == board[i][j] && board[i+2][j] == board[i][j])
                    || (j > 0 && Math.abs(board[i][j-1]) == board[i][j] && (j < n - 1 && board[i][j+1] == board[i][j]))
                    || (j > 1 && Math.abs(board[i][j-1]) == board[i][j] && Math.abs(board[i][j-2]) == board[i][j])
                    || (j < n - 2 && board[i][j+1] == board[i][j] && board[i][j+2] == board[i][j])) {
                    cnt++;
                    board[i][j] = -board[i][j];
                }
            }
        }
        for (int j = 0; j < n; j++) {
            int ptr = m - 1;
            for (int i = m - 1; i >= 0; i--) {
                if (board[i][j] > 0) {
                    board[ptr--][j] = board[i][j];
                }
            }
            for (int i = ptr; i >= 0; i--) {
                board[i][j] = 0;
            }
        }
        if (cnt == 0) {
            return board;
        } else {
            return candyCrush(board);
        }
    }
https://www.cnblogs.com/lightwindy/p/9744174.html
    vector<vector<int>> candyCrush(vector<vector<int>>& board) {
        const auto R = board.size(), C = board[0].size();
        bool changed = true;
         
        while (changed) {
            changed = false;
             
            for (int r = 0; r < R; ++r) {
                for (int c = 0; c + 2 < C; ++c) {
                    auto v = abs(board[r][c]);
                    if (v != 0 && v == abs(board[r][c + 1]) && v == abs(board[r][c + 2])) {
                        board[r][c] = board[r][c + 1] = board[r][c + 2] = -v;
                        changed = true;
                    }
                }
            }
             
            for (int r = 0; r + 2 < R; ++r) {
                for (int c = 0; c < C; ++c) {
                    auto v = abs(board[r][c]);
                    if (v != 0 && v == abs(board[r + 1][c]) && v == abs(board[r + 2][c])) {
                        board[r][c] = board[r + 1][c] = board[r + 2][c] = -v;
                        changed = true;
                    }
                }
            }
            for (int c = 0; c < C; ++c) {
                int empty_r = R - 1;
                for (int r = R - 1; r >= 0; --r) {
                    if (board[r][c] > 0) {
                        board[empty_r--][c] = board[r][c];
                    }
                }
                for (int r = empty_r; r >= 0; --r) {
                    board[r][c] = 0;
                }
            }
        }
         
        return board;
    }





X. http://storypku.com/2017/11/leetcode-question-723-candy-crush/
    vector<vector<int>> candyCrush(vector<vector<int>>& board) {
        int m = board.size(), n = board[0].size();
        bool toBeContinued = false;
        
        for (int i = 0; i < m; ++i) { // horizontal crushing
            for (int j = 0; j + 2 < n; ++j) {
                int& v1 = board[i][j];
                int& v2 = board[i][j+1];
                int& v3 = board[i][j+2];
                
                int v0 = std::abs(v1);
                
                if (v0 && v0 == std::abs(v2) && v0 == std::abs(v3)) {
                    v1 = v2 = v3 = - v0;
                    toBeContinued =  true;
                }
            }
        }
        
        for (int i = 0; i + 2 < m; ++i) {  // vertical crushing
            for (int j = 0; j < n; ++j) {
                int& v1 = board[i][j];
                int& v2 = board[i+1][j];
                int& v3 = board[i+2][j];
                int v0 = std::abs(v1);
                if (v0 && v0 == std::abs(v2) && v0 == std::abs(v3)) {
                    v1 = v2 = v3 = -v0;
                    toBeContinued = true;
                }
            }
        }
        
        for (int j = 0; j < n; ++j) { // gravity step
            int dropTo = m - 1;
            for (int i = m - 1; i >= 0; --i) {
                if (board[i][j] >= 0) {
                    board[dropTo--][j] = board[i][j];
                }
            }
            
            for (int i = dropTo; i >= 0; i--) {
                board[i][j] = 0;
            }
        }
        
        return toBeContinued ? candyCrush(board) : board;
        
    }




Labels

LeetCode (1432) GeeksforGeeks (1122) LeetCode - Review (1067) Review (882) Algorithm (668) to-do (609) Classic Algorithm (270) Google Interview (237) Classic Interview (222) Dynamic Programming (220) DP (186) Bit Algorithms (145) POJ (141) Math (137) Tree (132) LeetCode - Phone (129) EPI (122) Cracking Coding Interview (119) DFS (115) Difficult Algorithm (115) Lintcode (115) Different Solutions (110) Smart Algorithm (104) Binary Search (96) BFS (91) HackerRank (90) Binary Tree (86) Hard (79) Two Pointers (78) Stack (76) Company-Facebook (75) BST (72) Graph Algorithm (72) Time Complexity (69) Greedy Algorithm (68) Interval (63) Company - Google (62) Geometry Algorithm (61) Interview Corner (61) LeetCode - Extended (61) Union-Find (60) Trie (58) Advanced Data Structure (56) List (56) Priority Queue (53) Codility (52) ComProGuide (50) LeetCode Hard (50) Matrix (50) Bisection (48) Segment Tree (48) Sliding Window (48) USACO (46) Space Optimization (45) Company-Airbnb (41) Greedy (41) Mathematical Algorithm (41) Tree - Post-Order (41) ACM-ICPC (40) Algorithm Interview (40) Data Structure Design (40) Graph (40) Backtracking (39) Data Structure (39) Jobdu (39) Random (39) Codeforces (38) Knapsack (38) LeetCode - DP (38) Recursive Algorithm (38) String Algorithm (38) TopCoder (38) Sort (37) Introduction to Algorithms (36) Pre-Sort (36) Beauty of Programming (35) Must Known (34) Binary Search Tree (33) Follow Up (33) prismoskills (33) Palindrome (32) Permutation (31) Array (30) Google Code Jam (30) HDU (30) Array O(N) (29) Logic Thinking (29) Monotonic Stack (29) Puzzles (29) Code - Detail (27) Company-Zenefits (27) Microsoft 100 - July (27) Queue (27) Binary Indexed Trees (26) TreeMap (26) to-do-must (26) 1point3acres (25) GeeksQuiz (25) Merge Sort (25) Reverse Thinking (25) hihocoder (25) Company - LinkedIn (24) Hash (24) High Frequency (24) Summary (24) Divide and Conquer (23) Proof (23) Game Theory (22) Topological Sort (22) Lintcode - Review (21) Tree - Modification (21) Algorithm Game (20) CareerCup (20) Company - Twitter (20) DFS + Review (20) DP - Relation (20) Brain Teaser (19) DP - Tree (19) Left and Right Array (19) O(N) (19) Sweep Line (19) UVA (19) DP - Bit Masking (18) LeetCode - Thinking (18) KMP (17) LeetCode - TODO (17) Probabilities (17) Simulation (17) String Search (17) Codercareer (16) Company-Uber (16) Iterator (16) Number (16) O(1) Space (16) Shortest Path (16) itint5 (16) DFS+Cache (15) Dijkstra (15) Euclidean GCD (15) Heap (15) LeetCode - Hard (15) Majority (15) Number Theory (15) Rolling Hash (15) Tree Traversal (15) Brute Force (14) Bucket Sort (14) DP - Knapsack (14) DP - Probability (14) Difficult (14) Fast Power Algorithm (14) Pattern (14) Prefix Sum (14) TreeSet (14) Algorithm Videos (13) Amazon Interview (13) Basic Algorithm (13) Codechef (13) Combination (13) Computational Geometry (13) DP - Digit (13) LCA (13) LeetCode - DFS (13) Linked List (13) Long Increasing Sequence(LIS) (13) Math-Divisible (13) Reservoir Sampling (13) mitbbs (13) Algorithm - How To (12) Company - Microsoft (12) DP - Interval (12) DP - Multiple Relation (12) DP - Relation Optimization (12) LeetCode - Classic (12) Level Order Traversal (12) Prime (12) Pruning (12) Reconstruct Tree (12) Thinking (12) X Sum (12) AOJ (11) Bit Mask (11) Company-Snapchat (11) DP - Space Optimization (11) Dequeue (11) Graph DFS (11) MinMax (11) Miscs (11) Princeton (11) Quick Sort (11) Stack - Tree (11) 尺取法 (11) 挑战程序设计竞赛 (11) Coin Change (10) DFS+Backtracking (10) Facebook Hacker Cup (10) Fast Slow Pointers (10) HackerRank Easy (10) Interval Tree (10) Limited Range (10) Matrix - Traverse (10) Monotone Queue (10) SPOJ (10) Starting Point (10) States (10) Stock (10) Theory (10) Tutorialhorizon (10) Kadane - Extended (9) Mathblog (9) Max-Min Flow (9) Maze (9) Median (9) O(32N) (9) Quick Select (9) Stack Overflow (9) System Design (9) Tree - Conversion (9) Use XOR (9) Book Notes (8) Company-Amazon (8) DFS+BFS (8) DP - States (8) Expression (8) Longest Common Subsequence(LCS) (8) One Pass (8) Quadtrees (8) Traversal Once (8) Trie - Suffix (8) 穷竭搜索 (8) Algorithm Problem List (7) All Sub (7) Catalan Number (7) Cycle (7) DP - Cases (7) Facebook Interview (7) Fibonacci Numbers (7) Flood fill (7) Game Nim (7) Graph BFS (7) HackerRank Difficult (7) Hackerearth (7) Inversion (7) Kadane’s Algorithm (7) Manacher (7) Morris Traversal (7) Multiple Data Structures (7) Normalized Key (7) O(XN) (7) Radix Sort (7) Recursion (7) Sampling (7) Suffix Array (7) Tech-Queries (7) Tree - Serialization (7) Tree DP (7) Trie - Bit (7) 蓝桥杯 (7) Algorithm - Brain Teaser (6) BFS - Priority Queue (6) BFS - Unusual (6) Classic Data Structure Impl (6) DP - 2D (6) DP - Monotone Queue (6) DP - Unusual (6) DP-Space Optimization (6) Dutch Flag (6) How To (6) Interviewstreet (6) Knapsack - MultiplePack (6) Local MinMax (6) MST (6) Minimum Spanning Tree (6) Number - Reach (6) Parentheses (6) Pre-Sum (6) Probability (6) Programming Pearls (6) Rabin-Karp (6) Reverse (6) Scan from right (6) Schedule (6) Stream (6) Subset Sum (6) TSP (6) Xpost (6) n00tc0d3r (6) reddit (6) AI (5) Abbreviation (5) Anagram (5) Art Of Programming-July (5) Assumption (5) Bellman Ford (5) Big Data (5) Code - Solid (5) Code Kata (5) Codility-lessons (5) Coding (5) Company - WMware (5) Convex Hull (5) Crazyforcode (5) DFS - Multiple (5) DFS+DP (5) DP - Multi-Dimension (5) DP-Multiple Relation (5) Eulerian Cycle (5) Graph - Unusual (5) Graph Cycle (5) Hash Strategy (5) Immutability (5) Java (5) LogN (5) Manhattan Distance (5) Matrix Chain Multiplication (5) N Queens (5) Pre-Sort: Index (5) Quick Partition (5) Quora (5) Randomized Algorithms (5) Resources (5) Robot (5) SPFA(Shortest Path Faster Algorithm) (5) Shuffle (5) Sieve of Eratosthenes (5) Strongly Connected Components (5) Subarray Sum (5) Sudoku (5) Suffix Tree (5) Swap (5) Threaded (5) Tree - Creation (5) Warshall Floyd (5) Word Search (5) jiuzhang (5)

Popular Posts