【DFS之搜索顺序】洛谷P1123 取数游戏

P1123 取数游戏
搜索顺序:按格子枚举。
思想类比AcWing 843. n-皇后问题按格子枚举方法,以及
AcWing 1116. 马走日
AcWing 1117. 单词接龙
AcWing 1118. 分成互质组
,体会恢复现场写在for循环内部与写在for循环外部的区别。
最大的区别:恢复现场写在for循环外可以不用清空标记数组。恢复现场写在for循环内,则对于每组数据必须清空标记数组

参考链接:
https://www.acwing.com/activity/content/code/content/134135/
https://www.acwing.com/solution/content/6033/


C++代码

#include <iostream>
#include <cstring>

using namespace std;

const int N = 10;

int n, m, T, cnt, ans;
int g[N][N], st[N][N];
int dx[8] = {1, 1, 1, 0, -1, -1, -1, 0};
int dy[8] = {1, 0, -1, -1, -1, 0, 1, 1};

void dfs(int x, int y)
{
    if (y == m) y = 0, x++;//m列,y==m到达列末尾
    if (x == n)
    {
        ans = max(ans, cnt);
        return;
    }
    //不选此数
    dfs(x, y + 1);
    //选此数
    if (st[x][y] == 0)
    {
        cnt += g[x][y];
        for (int i = 0; i < 8; i++)
        {
            int a = x + dx[i], b = y + dy[i];
            if (a < 0 || a >= n || b < 0 || b >= m) continue;
            st[a][b]++;
        }
        dfs(x, y + 1);
        
        for (int i = 0; i < 8; i++) //恢复现场
        {
            int a = x + dx[i], b = y + dy[i];
            if (a < 0 || a >= n || b < 0 || b >= m) continue;
            st[a][b]--;
        }
        cnt -= g[x][y];
    }
}

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0), cout.tie(0);

    cin >> T;
    while (T--)
    {
        // 恢复现场在for循环外,可以不清空st,因为恢复现场会清空
        // memset(st, 0, sizeof st);
        cin >> n >> m;
        for (int i = 0; i < n; i++)
            for (int j = 0; j < m; j++)
                cin >> g[i][j];

        ans = 0;
        dfs(0, 0);
        cout << ans << '\n';
    }
    return 0;
}
posted @   Tshaxz  阅读(2)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 在鹅厂做java开发是什么体验
· 百万级群聊的设计实践
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战
· 永远不要相信用户的输入:从 SQL 注入攻防看输入验证的重要性
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
Language: HTML
点击右上角即可分享
微信分享提示