CodeForce-812B Sagheer, the Hausmeister(DFS)

Sagheer, the Hausmeister

CodeForces - 812B

题意:有一栋楼房,里面有很多盏灯没关,为了节约用电小L决定把这些灯都关了。

这楼有 n 层,最左边和最右边有楼梯。每一层有 m 个房间排成一排。这栋楼可以被表示成一个 nm + 2 列的矩阵,其中每行第一个和最后一个格点表示楼梯, 剩余 m 个格点表示房间。

现在小L在最底层的最左边楼梯,他想要关掉所有的灯。他每次可以走到相邻的房间,如果在楼梯口可以上下楼梯。他打算关掉所有开着的灯,在他没有将一层的所有灯都关闭前他不会上楼。现在求他最少需要走多少步可以关闭所有灯。

注意小L不需要返回原处,最终可以停留在任意一个地方。

直接dfs所有的状态:

#include<iostream>
#include<cstdio>
#include<string>
#include<algorithm>
using namespace std;
int n,m;
char mapp[20][110];
int dfs(int cnt,int pos,int temp)//cnt表示楼层,pos表示是哪边的楼梯,temp表示的是上楼要走多少步
{
    if(cnt<0) return 0;
    int ans=0;
    if(pos)
    {
        for(int i=m+2;i>=0;i--)
        {
            if(mapp[cnt][i]=='1')
            {
                ans+=pos-i+temp;
                pos=i;
                temp=0;
            }
        }
    }
    else
    {
        for(int i=0;i<m+2;i++)
        {
            if(mapp[cnt][i]=='1')
            {
                ans+=i-pos+temp;
                pos=i;
                temp=0;
            }
        }
    }
    ans+=min(dfs(cnt-1,0,temp+pos+1),dfs(cnt-1,m+1,temp+m+2-pos));
    return ans;
}

int main() {
    cin.sync_with_stdio(false);
    while (cin >> n >> m) {
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m + 2; j++) {
                cin >> mapp[i][j];
            }
        }
        cout << dfs(n-1,0,0) << endl;
    }
    return 0;
}
原文地址:https://www.cnblogs.com/YingZhixin/p/7102921.html