题意:从一个点出发,可以上下左右移动,移动的前提是,方向上至少有一个灯是亮的,每次到达一个位置,可以把灯点亮或者关掉,输出一组解能把所有的等都关掉,并且回到起点。
直接搜索一遍就好了,
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <queue>
using namespace std;
const int MAXN = 510;
const int MAXL = 3000010;
int mat[MAXN][MAXN];
bool vis[MAXN][MAXN];
char ans[MAXL];
int cnt, n, x0, y0;
void dfs(int x, int y) {
vis[x][y] = true;
if(!mat[x][y]) {
mat[x][y] = 1;
ans[cnt++] = '1';
}
for(int i = x - 1; i > 0; --i) {
if(mat[i][y] == 1) {
if(!vis[x - 1][y]) {
ans[cnt++] = 'U';
dfs(x - 1, y);
ans[cnt++] = 'D';
}
break;
}
}
for(int i = x + 1; i <= n; ++i) {
if(mat[i][y] == 1) {
if(!vis[x + 1][y]) {
ans[cnt++] = 'D';
dfs(x + 1, y);
ans[cnt++] = 'U';
}
break;
}
}
for(int i = y - 1; i > 0; --i) {
if(mat[x][i] == 1) {
if(!vis[x][y - 1]) {
ans[cnt++] = 'L';
dfs(x, y - 1);
ans[cnt++] = 'R';
}
break;
}
}
for(int i = y + 1; i <= n; ++i) {
if(mat[x][i] == 1) {
if(!vis[x][y + 1]) {
ans[cnt++] = 'R';
dfs(x, y + 1);
ans[cnt++] = 'L';
}
break;
}
}
mat[x][y] = 0;
ans[cnt++] = '2';
}
bool check() {
for(int i = 1; i <= n; ++i)
for(int j = 1; j <= n; ++j)
if(mat[i][j] == 1) return false;
return true;
}
int main() {
scanf("%d%d%d", &n, &x0, &y0);
for(int i = 1; i <= n; ++i)
for(int j = 1; j <= n; ++j) scanf("%d", &mat[i][j]);
dfs(x0, y0);
ans[cnt++] = 0;
if(check()) printf("YES\n%s\n", ans);
else puts("NO");
}
本文介绍了一个寻找路径的算法,该算法能够确保从任意起点出发,通过点亮和熄灭灯的方式,最终达到关闭所有灯并返回起点的目标。文章提供了一段C++代码实现,通过深度优先搜索遍历地图上的每个点,确保所有灯被关闭。
466

被折叠的 条评论
为什么被折叠?



