算法問題實戰策略 BOARDCOVER

地址 https://algospot.com/judge/problem/read/BOARDCOVERios

解法 函數

DFS 最近彷佛在簡單DFS上花費太多時間了oop

首先掃描地圖 統計可覆蓋的元素個數 若是不是3的倍數 那確定不能覆蓋徹底 返回0 spa

而後進行DFS 嘗試各類覆蓋辦法 一共12種(因爲必須覆蓋完全部元素 就規定從左上角開始覆蓋,其實能夠只有四種覆蓋辦法)code

 

每次DFS結束則覆蓋方法增長1種  嘗試全部覆蓋方式後 函數也返回blog

注意須要尋找每次下一個嘗試的覆蓋點 規定從左上角開始找起 ci

代碼get

// 11111111111111.cpp : 此文件包含 "main" 函數。程序執行將在此處開始並結束。
//




#include <iostream>
#include <vector>



using namespace std;

const int N = 30;

char gmap[N][N];

int loop;
int ans = 0;
int n, m;

struct board {
    int x1, y1;
    int x2, y2;
    int x3, y3;
};

vector<struct board> fillBoad=
{
    {0,0, -1,0, 0,-1},
    {0,0, 1,0,  0,-1},
    {0,0, -1,0, 0,1},
    {0,0, 1,0,  0,1},

    {0,0, 1,0,  1,-1},
    {0,0, -1,0, -1,-1},
    {0,0, 1,0,  1,1},
    {0,0, -1,0, -1,1},

    {0,0, 0,1,  -1,1},
    {0,0, 0,1,  1,1},
    {0,0, 0,-1, 1,-1},
    {0,0, 0,-1, -1-1},
};


bool CheckXY(int x1, int y1, int x2, int y2, int x3, int y3)
{
    if (x1 < 0 || y1 < 0 || x2 < 0 || y2 < 0 || x3 < 0 || y3 < 0)
        return false;

    if (x1 >= n || x2 >= n || x3 >= n || y1 >= m || y2 >= m || y3 >= m)
        return false;

    if (gmap[x1][y1] == '#' || gmap[x2][y2] == '#' || gmap[x3][y3] == '#')
        return false;


    return true;
}

void DFS(int x, int y,int needfill)
{
    if (needfill == 0) {
        ans++;
        return;
    }

    for (; x < n; x++) {
        for ( y = 0; y < m; y++) {
            if (gmap[x][y] == '.')
                goto FIND;
        }
    }
    FIND:


    for (int i = 0; i < 12; i++) {


        int newx1 = x + fillBoad[i].x1;  
        int newy1 = y + fillBoad[i].y1;
        int newx2 = x + fillBoad[i].x2;
        int newy2 = y + fillBoad[i].y2; 
        int newx3 = x + fillBoad[i].x3; 
        int newy3 = y + fillBoad[i].y3;

        if (CheckXY(newx1, newy1, newx2, newy2, newx3,newy3)) {
            gmap[newx1][newy1] = '#';
            gmap[newx2][newy2] = '#';
            gmap[newx3][newy3] = '#';
            needfill -= 3; 
            
            int p = x; int q = y;
            for (; p < n; p++) {
                for ( q = 0; q < m; q++) {
                    if (gmap[p][q] == '.')
                        goto FIND1;
                }
            }

            FIND1:

            DFS( p,q, needfill);

            needfill += 3; 
            gmap[newx1][newy1] = '.';
            gmap[newx2][newy2] = '.';
            gmap[newx3][newy3] = '.';

        }
    }


    return;
}

int main()
{
    cin >> loop;

    while (loop--)
    {
        cin >> n >> m;

        memset(gmap,0,N*N);
        ans = 0;

        int count = 0;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                cin >> gmap[i][j];
                if (gmap[i][j] == '.')
                    count++;
            }
        }

        if (count % 3 != 0){
            cout << 0 << endl;
            continue;
        }

        DFS(0,0,count);
        cout << ans << endl;
    }

    return 0;
}

acio

相關文章
相關標籤/搜索