計蒜客藍橋 B組第一場 第九題 摳圖

題意:將沒有被0 包裹的像素點全部變成 0,並且確保 0 構成的是矩形或者是矩形少一條邊,不會出現包含和相交

遍歷矩陣的邊緣

,從每一個不爲0的 邊緣開始dfs,即可將整個圖掃描完,因爲 不會出現相交的矩形,遍歷不到的地方只可能是靠邊圍起來的矩形,所以,沿着邊dfs絕對能遍歷完;

#include<bits/stdc++.h>
using namespace std;

struct node{
	int x,y;
}s[2005];

int f[4][2]={1,0,0,1,-1,0,0,-1};
int a[505][505];
int n,m;
void dfs(int x,int y){
	
	for(int i=0;i<4;i++){
		int x1=x+f[i][0];
		int y1=y+f[i][1];
		if(x1>=0&&y1>=0&&x1<n&&y1<m&&a[x1][y1]>0){
			a[x1][y1]=0;
			dfs(x1,y1);
		}
	}
}
int main(){
	int t;
	cin>>t;
	while(t--){
	
		int len=0;
		cin>>n>>m;
	
		for(int i=0;i<n;i++){
			for(int j=0;j<m;j++){
				cin>>a[i][j];
				if(a[i][j]>0&&(i==0||j==0||i==n-1||j==m-1)){
					s[len].x=i;
					s[len].y=j;
					len++;
					a[i][j]=0;
				}
			}
		}
		
		while(len--){
			dfs(s[len].x,s[len].y);
		}
		
		for(int i=0;i<n;i++){
			for(int j=0;j<m;j++){
				cout<<a[i][j];
				if(j<m-1)cout<<" ";
			}
			cout<<endl;
		}
		
		
	}
} 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章