ACM PKU 1562 Oil Deposits

本文详细对比了两种不同的程序实现方式在POJ 1562题目上的表现,一种通过整行读取输入并成功AC,另一种逐字符读取导致WA。通过对两种方式的代码进行分析,探讨了可能的问题所在。

题目链接:http://poj.org/problem?id=1562

这道题相当尴尬了,两个一样的程序换个输入就A了,改成一个个字母读入就wa了,不知道为什么,希望大家能指出错误之处,不胜感激;

AC的代码:

#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;

const int maxn=100;
char ch[maxn+10][maxn+10];
int r[8]= {0,-1,-1,-1,0,1,1,1},c[8]= {1,1,0,-1,-1,-1,0,1};
int m,n,ans;

bool charge(int x,int y)
{
    if(x<0||y<0||x>=m||y>=n||ch[x][y]=='*') return false;
    return true;
}

void dfs(int x,int y)
{
    ch[x][y]='*';
    for(int i=0; i<8; i++)
    {
        int a=x+r[i];
        int b=y+c[i];
        if(charge(a,b)) dfs(a,b);
    }
    return;
}

int main()
{
    //freopen("in.txt","r",stdin);
    while(scanf("%d%d",&m,&n)&&m)
    {
        ans=0;
        getchar();
        for(int i=0; i<m; i++)
        {
                scanf("%s",ch[i]);
        }
        for(int i=0; i<m; i++)
            for(int j=0; j<n; j++)
                if(ch[i][j]=='@')
                {
                    dfs(i,j);
                    ans++;
                }
        printf("%d\n",ans);
    }
    return 0;
}

wa了的代码:

#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;

const int maxn=100;
char ch[maxn+10][maxn+10];
int r[8]= {0,-1,-1,-1,0,1,1,1},c[8]= {1,1,0,-1,-1,-1,0,1};
int m,n,ans;

bool charge(int x,int y)
{
    if(x<0||y<0||x>=m||y>=n||ch[x][y]=='*') return false;
    return true;
}

void dfs(int x,int y)
{
    ch[x][y]='*';
    for(int i=0; i<8; i++)
    {
        int a=x+r[i];
        int b=y+c[i];
        if(charge(a,b)) dfs(a,b);
    }
    return;
}

int main()
{
//    freopen("in.txt","r",stdin);
    while(scanf("%d%d",&m,&n)&&m)
    {
        ans=0;
        getchar();
        for(int i=0; i<m; i++)
        {
            for(int j=0;j<n;j++)
                scanf("%c",&ch[i][j]);
                getchar();
        }
        for(int i=0; i<m; i++)
            for(int j=0; j<n; j++)
                if(ch[i][j]=='@')
                {
                    dfs(i,j);
                    ans++;
                }
        printf("%d\n",ans);
    }
    return 0;
}


 

 

转载于:https://www.cnblogs.com/Chinese-Coder-Clarence/articles/2185474.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值