Nearest number - 2
Time Limit: 5000MS Memory Limit: 65536K
Total Submissions: 4100 Accepted: 1275
Description
Input is the matrix A of N by N non-negative integers.
A distance between two elements Aij and Apq is defined as |i − p| + |j − q|.
Your program must replace each zero element in the matrix with the nearest non-zero one. If there are two or more nearest non-zeroes, the zero must be left in place.
Constraints
1 ≤ N ≤ 200, 0 ≤ Ai ≤ 1000000
Input
Input contains the number N followed by N2 integers, representing the matrix row-by-row.
Output
Output must contain N2 integers, representing the modified matrix row-by-row.
Sample Input
3
0 0 0
1 0 2
0 3 0
Sample Output
1 0 2
1 0 2
0 3 0
有DP的方法,效率是O(n^2),但是我想不出,也没看到有博客是用DP,所以就暴力了。
#include <iostream>
#include <string.h>
#include <algorithm>
#include <math.h>
#include <stdlib.h>
#include <queue>
using namespace std;
int a[205][205];
int b[205][205];
int vis[205][205];
int dir[4][2]={{1,0},{0,1},{-1,0},{0,-1}};
int n;
int c[405];
int d[405];
struct Node
{
int x,y;
};
void bfs(int x,int y)
{
Node Q[40005];
int rear=0,front=0;
int flag=0,level=9999999;
//Queue.push(Node(x,y));
Node term;
term.x=x;
term.y=y;
Q[rear++]=term;
vis[x][y]=1;
while(rear!=front&&flag!=-1)
{
// Node temp=Queue.front();
//Queue.pop();
Node temp=Q[front++];
if(level<=vis[temp.x][temp.y])
break;
for(int i=0;i<4;i++)
{
int xx=temp.x+dir[i][0];
int yy=temp.y+dir[i][1];
if(xx<0||xx>n-1||yy<0||yy>n-1||vis[xx][yy])
continue;
vis[xx][yy]=vis[temp.x][temp.y]+1;
if(a[xx][yy]!=0)
{
if(!flag)
{
flag=a[xx][yy];
level=vis[xx][yy];
}
else
{
flag=-1;
break;
}
}
//Queue.push(Node(xx,yy));
else
{
Node item;
item.x=xx;
item.y=yy;
Q[rear++]=item;
}
}
}
if(flag>0)
b[x][y]=flag;
}
void init()
{
memset(vis,0,sizeof(vis));
memset(c,0,sizeof(c));
}
int main()
{
while(scanf("%d",&n)!=EOF)
{
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
{scanf("%d",&a[i][j]);b[i][j]=a[i][j];}
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
{
if(a[i][j]==0)
{
init();
bfs(i,j);
}
}
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
if(j!=n-1)
printf("%d ",b[i][j]);
else
printf("%d",b[i][j]);
}
printf("
");
}
}
}