方格选数

计蒜客蓝桥杯集训营

/*
这道题并没有想到是dfs, 看到后首先就是人肉做, 但是很可惜错误了.
再经过被提示是dfs后, 我就想怎么去dfs呢?
最初想直接从 0, 0 开始, 直接这样搜全图,
但是这样的话, 不知道怎么去枚举所有的起始点, 也不知道怎么回溯...
后来突然想到, 枚举所有的点都为起点, 把从起始点开始所有一笔划sum < 25, 所有的product都记录就可以了
这样就比较简单了
*/
#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdio>
using namespace std;
const int maxn = 5;
int dir[][2] = {
    {0, 1},
    {0, -1},
    {1, 0},
    {-1, 0}
};
int ans;
int maze[][maxn] = {
    {3, 4, 5, 7, 6},
    {6, 2, 8, 4, 12},
    {7, 12, 4, 8, 3},
    {1, 9, 5, 10, 7},
    {8, 5, 6, 5, 2}
};
int visited[maxn][maxn];
void dfs(int r, int c, int sum, int product);
int main()
{
    for(int i = 0; i < maxn; ++i)
        for(int j = 0; j < maxn; ++j){
            memset(visited, false, sizeof(visited));
            visited[i][j] = true;
            dfs(i, j, maze[i][j], maze[i][j]);
        }
    printf("%d\n", ans);
	return 0;
}
void dfs(int r, int c, int sum, int product)
{
    if(sum < 25)
        ans = max(ans, product);
    else
        return;
    for(int i = 0; i < 4; ++i){
        int nr = r + dir[i][0];
        int nc = c + dir[i][1];
        if(0 <= nr && nr < 5 && 0 <= nc && nc < 5)
            if(!visited[nr][nc] && sum + maze[nr][nc] < 25){
                visited[nr][nc] = true;
                dfs(nr, nc, sum + maze[nr][nc], product * maze[nr][nc]);
                visited[nr][nc] = false;
            }
    }
}

猜你喜欢

转载自blog.csdn.net/u013482363/article/details/79419713