POJ 2329 (暴力+搜索bfs)
来源:互联网 发布:mac word文件丢失 编辑:程序博客网 时间:2024/04/30 10:57
Nearest number - 2
Time Limit: 5000MSMemory Limit: 65536KTotal Submissions: 3943Accepted: 1210
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
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
30 0 01 0 20 3 0
Sample Output
1 0 21 0 20 3 0
#include<iostream>#include<cstdio>using namespace std;int n;int matri[210][210];int dx[]={1,1,-1,-1},cx[]={-1,0,1,0};int dy[]={-1,1,1,-1},cy[]={0,-1,0,1};bool in_matrix(int x,int y){ if(x<0||x>=n) return false; if(y<0||y>=n) return false; return true;}int bfs(int x,int y,int k){ if(k>n) return 0; //n*n matrix搜索K次,自己可以特值来理解 if(matri[x][y]||n==1) return matri[x][y]; //数不为0,或只有一个数(即 1*1 矩阵),就输出 int xx,yy,X,Y; int i,j; int cnt=0,die=0; for(i=0;i<4;i++) //对于菱形4条边的搜索,这里是以每边K个数字来写。 { xx=x+k*cx[i]; yy=y+k*cy[i]; for(j=k;j--;) //相当于for(j=0;j<k;j++),一边k个数,所以搜索k次 { if(in_matrix(xx,yy)&&matri[xx][yy]) { if(cnt==1) { die=1; break; } X=xx; Y=yy; cnt++; } xx+=dx[i]; yy+=dy[i]; } if(die) break; } if(cnt==0) return bfs(x,y,k+1); else if(die) return 0; else return matri[X][Y];}int main(){ scanf("%d",&n); for(int i = 0; i < n; ++i) for(int j = 0; j < n; ++j) scanf("%d",&matri[i][j]); for(int i = 0; i < n; ++i,printf("\n")) for(int j = 0; j < n; ++j) printf("%d ",bfs(i,j,1)); return 0;}
(借鉴大大的思路)
值得学习的是,对于矩阵的逆时针菱形搜索,思考了很长时间都没有想清楚。
自己可以试一下顺时针,一样的道理哦。
int dx[]={1,1,-1,-1},cx[]={-1,0,1,0};
int dy[]={-1,1,1,-1},cy[]={0,-1,0,1};
主要是这两对数组,用的很是巧妙!
0 0
- POJ 2329 (暴力+搜索bfs)
- POJ 3697 BFS暴力
- poj 3278 暴力BFS
- FZU2150双源BFS,暴力搜索
- POJ 1166 The Clocks(暴力搜索)
- POJ-1414 Life Line (暴力搜索)
- POJ 1129 Channel Allocation (暴力搜索)
- POJ 1380 暴力搜索
- POJ 1054 暴力搜索
- POJ 1753 (暴力搜索)
- POJ 3278(BFS-搜索范围)
- POJ 3414 Pots (BFS搜索题)
- poj 3126 Prime Path(bfs搜索)
- poj 3278(bfs宽度优先搜索)
- POJ 2251 Dungeon Master (搜索 -- BFS)
- poj 3414 搜索BFS
- poj 2243 BFS搜索
- POJ 1077 八数码(康托展开+暴力bfs)
- 如何使用Git上传项目代码到代码服务器
- Python-操作Excel
- Python基础编程(九)魔法方法、属性和迭代器
- Ormlite开源数据库框架
- 12.3
- POJ 2329 (暴力+搜索bfs)
- textarea计算输入字符大小并限制输入
- 算法学习十八----寻找发帖水王
- leetcode Largest Rectangle in Histogram
- 3.1 创建线程执行器
- OpenCV_读取文件夹下的图片生成视频文件
- UML视图(五)活动图
- DELETE、TRUNCATE与高水位线(HWM)
- 《贺新郎.读史》 —— 毛泽东