計蒜客 A1627 連連看 暴力搜索

題目描述

原題連接html

連連看是一款很是有意思的遊戲。
在這裏插入圖片描述
咱們能夠把任意兩個在圖的在邊界上的相同的方格一塊兒消掉,好比把兩個 4 4 4消掉之後
在這裏插入圖片描述
在這裏插入圖片描述
每次消掉兩個方格的時候,都有會得到一個分數,第 i i i 次消的分數爲 i × i× i×方格的值。好比上面的消法,是第一次消,得到的分數爲 1 × 4 = 4 1×4=4 1×4=4
請你幫忙最優操做狀況下,得到的分數最多爲多少。ios

分析

結果填空題, 不用考慮時間複雜度,直接暴力搜索
注意, 每次只能消掉邊界上值相同的兩個格子web

答案

分數最大爲 89 89 89svg

實現

// 跑了十多分鐘尚未跑完, 複雜度實在過高了, 應該還能夠剪枝
// 答案一直停留在89
#include <cstdio>
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
int map[4][4] = {{1,4,2,5},{2,1,2,1},{3,1,3,2},{2,5,3,4}};
bool vis[4][4]; // 是否已經被消除
int dx[] = {0,1,0,-1}, dy[] = {1,0,-1,0};
int ans = -1;
bool check(int x, int y) // 檢查當前格子是否爲邊界
{
    if(vis[x][y]) return false; // 格子已經被消除過
    for(int i=0; i<4; i++)
    {
        int nx = x + dx[i], ny = y + dy[i];
        if(nx < 0 || nx >= 4 || ny < 0 || ny >= 4) return true; // 上下左右的格子存在出界的狀況, 則當前的格子必定是邊界
        if(vis[nx][ny]) return true; // 上下左右的格子存在被消除的狀況, 則當前的格子必定是邊界
    }
    return false;
}
void dfs(int step, int score)
{
    cout << ans << endl;
    ans = max(ans, score); // 更新最高得分
    for(int i=0; i<4; i++)
    {
        for(int j=0; j<4; j++)
        {
            if(!check(i,j)) continue;  // 遍歷整個地圖, 先找到一個爲邊界的格子
            for(int k=0; k<4; k++)
            {
                for(int p=0; p<4; p++)
                {
                    if((i==k && j==p) || !check(k,p) || map[i][j] != map[k][p]) continue; // 再遍歷整個地圖, 找到一個和[i,j]值相等且爲邊界的格子
                    vis[i][j] = vis[k][p] = 1;
                    dfs(step+1,score + step*map[i][j]);
                    vis[i][j] = vis[k][p] = 0; // 回溯
                }
            }
        }
    }
    return;
}
int main()
{
    dfs(1,0);
    cout << ans << endl;
    return 0;
}
相關文章
相關標籤/搜索