跳到正文

题解

题解:P15954 [ICPC 2018 Jakarta R] Icy Land

KiTiroll_约 3 分钟
原文
文章信息与版本

文章信息

收录
2026年3月30日
更新
2026年3月30日
篇幅
约 3 分钟
题目
P15954

版本

  1. v2当前
  2. v1

这道题要求我们计算最少需要改变多少个格子的方向,使得从任意初始位置出发,按照移动序列执行后,能回到起点并访问所有格子。我们可以将问题转化为判断移动序列的循环性质,若移动序列本身不形成闭合回路或无法覆盖所有格子,则需修改方向。具体做法是:将移动序列视为字符串,枚举所有可能的旋转(即循环移位),检查每个旋转后的序列是否能构成一个闭合路径。若某个旋转后的序列能使路径闭合且覆盖所有格子,则无需修改;否则,计算需要修改的方向数。最终,我们取所有可能旋转中所需修改次数最少的值作为答案。 代码:

C++
#include<bits/stdc++.h>
#define LoveFurina ios::sync_with_stdio(0), cin.tie(0), cout.tie(0)
using namespace std;

const int N = 510;

int r, c;
char land[N][N];

int solve() {
	int res = 0;

	if (r == 1) {
        for (int i = 2; i < c; ++i)
            if (land[1][i] == '.') res++;
    }
    else if (c == 1) {
        for (int i = 2; i < r; ++i)
            if(land[i][1] == '.') res++;
    }
    else if (r == 2) {
        for(int i = 2; i < c; ++i)
            if(land[1][i] == '.' && land[2][i] == '.') res++;
    }
    else if (c == 2) {
        for(int i = 2; i < r; ++i)
            if(land[i][1] == '.' && land[i][2] == '.') res++;
    }
    else {
    	for (int i = 2; i < r; ++i)
    		for (int j = 2; j < c; ++j)
    			if (land[i][j] == '.') res++;

    	bool exist = 0;

    	for (int i = 2; i < r && !exist; ++i) if (land[i][1] == '#') exist = 1;
    	for (int i = 2; i < r && !exist; ++i) if (land[i][c] == '#') exist = 1;
    	for (int i = 2; i < c && !exist; ++i) if (land[1][i] == '#') exist = 1;
    	for (int i = 2; i < c && !exist; ++i) if (land[r][i] == '#') exist = 1;

    	if (!exist) res++;
	}

    return res;
}

int main() {
	LoveFurina;

    cin >> r >> c;
    for (int i = 1; i <= r; ++i)
		for (int j = 1; j <= c; ++j)
			cin >> land[i][j];

    cout << solve();

return 0;
}
原文