bfs-抠图

在这里插入图片描述
在这里插入图片描述

import java.util.Scanner;
public class Main{
	public static void dfs(int x,int y,int[][]a) {
		if (x<0||y<0||x>w+1||y>h+1||a[x][y]==0) {
			return;
		}
		a[x][y]=0;
		dfs(x+1, y, a);
		dfs(x-1, y, a);
		dfs(x, y+1, a);
		dfs(x, y-1, a);
	}
	static int a[][];
	static int w=0;
	static int h=0;
	public static void main(String[] args) {
		Scanner scanner=new Scanner(System.in);
		int n=scanner.nextInt();
		w=scanner.nextInt();
		h=scanner.nextInt();
		a=new int[w+2][h+2];
		for(int i=1;i<=w;i++) {
			for(int j=1;j<=h;j++) {
				a[i][j]=scanner.nextInt();
			}
			a[i][0]=1;
			a[i][h+1]=1;
		}
		for (int i = 0; i <=h+1; i++) {
			a[0][i]=1;
			a[w+1][i]=1;
		}
		dfs(1, 1, a);
		for (int i = 1; i <= w; i++) {
			for (int j = 1; j <= h; j++) {
				System.out.print(a[i][j]+" ");
			}
			System.out.println();
		}
	}
}

import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;

public class 输出数字生成器 {
	static int W=1445;
	static int H=965;
	static int[][]dir= {{-1,0},{1,0},{0,-1},{0,1}};
	public static class node{
		int x,y;
		public node(int a,int b) {
			// TODO Auto-generated constructor stub
			x=a;
			y=b;
		}
	}
	static int w,h,t;
	static int a[][]=new int[H][W];
	static int v[][]=new int[H][W];
	static Queue<node> q;
	public static void bfs(int x0,int y0) {
		int i,x,y;
		q=new LinkedList<node>();
		while(!q.isEmpty()) {
			q.poll();
		}
		node p=new node(x0, y0);
		q.offer(p);
		v[x0][y0]=1; 
		while (!q.isEmpty()) { 
			p=q.peek(); 
			q.poll(); 
			for (i=0;i<=3;i++) { 
				x=p.x+dir[i][0]; 
				y=p.y+dir[i][1]; 
				if (check(x,y)&&v[x][y]==0) {
					v[x][y]=1; 
					q.offer(new node(x,y)); 
				} 
			} 
		}
	}
	public static boolean check(int x, int y) {
		if (x>0&&x<=h&&y>0&&y<=w&&a[x][y]!=0) {
			
			return true;
		}
		return false;
	}
	public static void main(String[] args) {
		int i,j,x0,y0,flag,cnt;
		Scanner scanner=new Scanner(System.in);
		t=scanner.nextInt();
		while(t>0) {
			t--;
			w=scanner.nextInt();
			h=scanner.nextInt();
			x0=0;y0=0;
			for (int k = 1; k <=h; k++) {
				for (int k2 = 1; k2 <=w; k2++) {
					a[k][k2]=scanner.nextInt();
					v[k][k2]=0;
					if (a[k][k2]==0&&x0==0) {
						x0=k+1;
						y0=k2+1;
					}
				}	
			}
			bfs(x0,y0);
			for (i=1;i<=h;i++) { 
				for (j=1;j<=w;j++) 
					if (v[i][j]==1) 
						System.out.printf("%d ",a[i][j]); 
					else 
						System.out.printf("0 "); 
				System.out.printf("\n"); 
			}		
		}
	}
}

发布了89 篇原创文章 · 获赞 42 · 访问量 3664

猜你喜欢

转载自blog.csdn.net/weixin_43673156/article/details/105026772