POJ 2329

题意:把矩阵n*n中所有的0改成它最接近的正数,若有两个及以上都满足,则不变。

题解:bfs每个0

View Code
 1 #include<cstdio>

 2 #include<cstring>

 3 #include<algorithm>

 4 using namespace std;

 5 const int N=50000;

 6 int map[300][300],ans[300][300];

 7 int po[N][2];

 8 int stk[N][3];

 9 int dr[][2]={0,1,0,-1,1,0,-1,0};

10 bool mark[300][300];

11 int main()

12 {

13     int n;

14     while(scanf("%d",&n)!=EOF)

15     {

16         int x,y,tx,ty,st,ed,num=0,t;

17         for(int i=1;i<=n;i++)

18             for(int j=1;j<=n;j++)

19             {

20                 scanf("%d",&map[i][j]);

21                 if(!map[i][j])

22                 {

23                     po[num][0]=i;

24                     po[num][1]=j;

25                     num++;

26                 }

27             }

28         memcpy(ans,map,sizeof(map));

29         for(int i=0;i<num;i++)

30         {

31             st=0,ed=1;

32             stk[0][0]=po[i][0];

33             stk[0][1]=po[i][1];

34             stk[0][2]=0;

35             int minstep=0,tp=0;

36             memset(mark,false,sizeof(mark));

37             while(st!=ed)

38             {

39                 x=stk[st][0];

40                 y=stk[st][1];

41                 t=stk[st][2];

42                 st++;

43                 if(st==N)

44                     st=0;

45                 if(map[x][y])

46                 {

47                     if(minstep==0)

48                         minstep=t,tp=map[x][y];

49                     else if(minstep==t)

50                     {

51                         tp=0;

52                         break;

53                     }

54                 }

55                 else if(minstep==0||minstep>t)

56                 {

57                     for(int j=0;j<4;j++)

58                     {

59                         tx=x+dr[j][0];

60                         ty=y+dr[j][1];

61                         if(tx>=1&&tx<=n&&ty>=1&&ty<=n&&!mark[tx][ty])

62                         {

63                             mark[tx][ty]=true;

64                             stk[ed][0]=tx;

65                             stk[ed][1]=ty;

66                             stk[ed][2]=t+1;

67                             ed++;

68                             if(ed==N)

69                                 ed=0;

70                         }

71                     }

72                 }

73             }

74             ans[po[i][0]][po[i][1]]=tp;

75         }

76         for(int i=1;i<=n;i++)

77         {

78             for(int j=1;j<=n;j++)

79             {

80                 if(j!=1)

81                     printf(" ");

82                 printf("%d",ans[i][j]);

83             }

84             printf("\n");

85         }

86     }

87     return 0;

88 }

你可能感兴趣的:(poj)