您的位置:首页 > 其它

CodeForces Gym 100646G The Worm Turns DFS

2016-07-22 00:10 459 查看
就是有一个矩阵,每个点要么有食物,要么是石头 ,然后有个人会从某一个点沿着某个方向吃食物,当下个地方不能走时它会向左或者向右转,他也不会再走已经走过的点,然后问他从哪里开始吃能吃到最多食物

就暴力枚举每个点以及四个方向,但是因为下个地方不能走时他既能向左又能向右,所以两个方向都有走,所以要DFS去搜所有情况,然后每个点每个方向都DFS一次就行

#include <cstdio>
#include <cstring>
#include <vector>
#include <iostream>
#include <string>
#include <cmath>
#include <algorithm>
#include <set>
#include <map>
#include <queue>
using namespace std;
#define ll long long
#define mod 1000000009
#define maxn 105
#define maxm 10003
#define INF 0x3f3f3f3f
const int dx[4] = { 0, -1, 1, 0 };
const int dy[4] = { 1, 0, 0, -1 };
int N, M;
char grid[630];
bool vis[630];
char d[4] = { 'E', 'N', 'S', 'W' };
struct Node
{
int x, y, dir, cnt;
Node()
{
x = 0; y = 0; dir = 0; cnt = 0;
}
Node(int x, int y,int dir, int cnt)
{
this->x = x; this->y = y; this->dir = dir; this->cnt = cnt;
}
};
queue<Node> Q;
int ans, ansdir, ansx, ansy;
int xi, yi, di;
void DFS(int ax,int ay,int dir, int step)
{
//printf("%d %d\t", ax, ay);
vis[ax*M + ay] = true;
int xx, yy;
xx = ax + dx[dir]; yy = ay + dy[dir];
if (xx >= 0 && xx < N&&yy >= 0 && yy < M&&grid[xx*M + yy] != 'X'&&!vis[xx*M + yy])
{
DFS(xx, yy, dir, step + 1);
}
else
{
bool expand = false;
int cnt = 1, d = dir + 1;
if (d >= 4)
d -= 4;
while (1)
{
if (cnt >= 4)
break;
xx = ax + dx[d]; yy = ay + dy[d];
if (xx >= 0 && xx < N&&yy >= 0 && yy < M&&grid[xx*M + yy] != 'X'&&!vis[xx*M + yy])
{
expand = true;
DFS(xx, yy, d, step + 1);
}
++cnt; ++d;
if (d >= 4)
d -= 4;
}
if (expand == false)
{
if (step > ans)
{
//printf("\nxi %d yi %d dir %d step %d xx %d yy %d\n", xi, yi, di, step, ax, ay);
ans = step; ansx = xi; ansy = yi; ansdir = di;
}
}
}
vis[ax*M + ay] = false;
}
int main()
{
//freopen("input.txt", "r", stdin);
int kase = 1;
while (scanf("%d%d",&N,&M)!=EOF)
{
if (N == 0 && M == 0)
break;
memset(grid, 0, sizeof(char) * 630);
int r;
scanf("%d", &r);
int xx, yy;
for (int i = 0; i < r; ++i)
{
scanf("%d%d", &xx, &yy);
grid[xx*M + yy] = 'X';
}

Node t;
ans = -1; ansdir = 0; ansx = 0; ansy = 0;
for (xi = 0; xi < N; ++xi)
{
for (yi = 0; yi < M; ++yi)
{
if (grid[xi*M + yi] == 'X')
continue;
for (di = 0; di < 4; ++di)
{
//printf("%d %d %d\n", i, j, k);
xx = xi + dx[di]; yy = yi + dy[di];
if (xx < 0 || xx >= N || yy < 0 || yy >= M || grid[xx*M + yy] == 'X')
continue;
memset(vis, 0, sizeof(vis));
DFS(xi, yi, di, 1);
}
}
}
printf("Case %d: %d %d %d %c\n", kase, ans, ansx, ansy, d[ansdir]);
++kase;
}
//system("pause");
//while (1);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: