您的位置:首页 > 其它

HDU 5335 - Walk Out (DFS + 贪心)

2015-07-31 15:34 260 查看
题目:

http://acm.hdu.edu.cn/showproblem.php?pid=5335

题意:

n*m的01矩阵,起点(1,1),终点(n,m)。求出走出的路径得到的最小的二进制。

思路:

贪心策略:

一开始能走0就走0,dfs走到离终点最近的0。接下来的路径应该尽可能短,且0尽可能多。

本题有一个很巧妙的地方:遍历到离终点最近的0(x+y = tot),接下来的最优答案便是每一条斜线一个位置,注意到每条斜线的x+y相等,所以从 tot~n+m 去查找最优的位置。

AC.

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#pragma comment(linker,"/STACK:1024000000,1024000000");
using namespace std;
int n, m;
char rec[1005][1005];
int f[1005][1005];
int tot;

int vis[1005][1005];
void dfs(int x, int y)
{
if(vis[x][y]) return;
vis[x][y] = 1;
if(rec[x][y] == '1') return;
f[x][y] = 1;
if(x+y > tot) tot = x+y;

if(x > 1) dfs(x-1, y);
if(x < n) dfs(x+1, y);
if(y > 1) dfs(x, y-1);
if(y < m) dfs(x, y+1);
}

void solve()
{
if(tot == n+m) {
printf("0\n");
return;
}

if(tot == 0) {
printf("1");
f[1][1] = 1;
tot = 2;
}
for(int i = tot; i < n+m; ++i) {
int flag = 1; //要赋值,可能没有进入循环。

for(int j = max(1, i-m); j <= min(n, i-1); ++j) {
if(f[j][i-j]) {
int x = j < n? rec[j+1][i-j] - '0': 1;
int y = i-j < m? rec[j][i-j+1] - '0': 1;
flag = min(flag, min(x, y));
}
}

for(int j = max(1, i-m); j <= min(n, i-1); ++j) {
if(f[j][i-j]) {
int x = j < n? rec[j+1][i-j] - '0': 1;
int y = i-j < m? rec[j][i-j+1] - '0': 1;

if(x == flag) f[j+1][i-j] = 1;
if(y == flag) f[j][i-j+1] = 1;
}
}

printf("%d", flag);
}
printf("\n");
}

void init()
{
memset(vis, 0, sizeof(vis));
memset(f, 0, sizeof(f));
tot = 0;
}

int main()
{
//freopen("in", "r", stdin);
int T;
scanf("%d", &T);
while(T--) {

scanf("%d %d", &n, &m);
for(int i = 1; i <= n; ++i) {
scanf("%s", rec[i]+1);
}

init();
dfs(1, 1);
solve();
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  HDU