【題目描述】
由數字0組成的方陣中,有一任意形狀閉合圈,閉合圈由數字1構成,圍圈時只走上下左右4個方向。現要求把閉合圈內的全部空間都填寫成2.例如:6 6×6的方陣(n=6),塗色前和塗色後的方陣以下:java
0 0 0 0 0 0
0 0 1 1 1 1
0 1 1 0 0 1
1 1 0 0 0 1
1 0 0 0 0 1
1 1 1 1 1 1測試
0 0 0 0 0 0
0 0 1 1 1 1
0 1 1 2 2 1
1 1 2 2 2 1
1 2 2 2 2 1
1 1 1 1 1 1
輸入格式
每組測試數據第一行一個整數n(1≤n≤30)code
接下來n行,由0和1組成的n×n的方陣。class
方陣內只有一個閉合圈,圈內至少有一個0。import
輸出格式
已經填好數字2的完整方陣。List
輸入輸出樣例
輸入
6
0 0 0 0 0 0
0 0 1 1 1 1
0 1 1 0 0 1
1 1 0 0 0 1
1 0 0 0 0 1
1 1 1 1 1 1
輸出
0 0 0 0 0 0
0 0 1 1 1 1
0 1 1 2 2 1
1 1 2 2 2 1
1 2 2 2 2 1
1 1 1 1 1 1
說明/提示
1≤n≤30map
先上代碼:im
import java.util.LinkedList; import java.util.Queue; import java.util.Scanner; public class Main { static int[][]vis = new int[40][40]; static int [][]map = new int[40][40]; static Queue<Integer> qx = new LinkedList<Integer>(); static Queue<Integer> qy = new LinkedList<Integer>(); static int []dx = {1,0,-1,0}; static int []dy = {0,1,0,-1}; static int n; public static boolean inmap(int x,int y) { return(x>=0&&x<=n+1&&y>=0&&y<=n+1); } public static void bfs(int x,int y) { while(!qx.isEmpty())//不爲空的狀態下 { for (int i = 0; i < 4; i++) { int xx = qx.peek()+dx[i]; int yy = qy.peek()+dy[i]; if(inmap(xx,yy)&&vis[xx][yy]!=1&&map[xx][yy]!=1) { qx.offer(xx); qy.offer(yy); vis[xx][yy] = 1; } } qx.poll(); qy.poll(); } } public static void main(String[] args) { Scanner s = new Scanner(System.in); n = s.nextInt(); for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { map[i][j] = s.nextInt(); } } qx.offer(0); qy.offer(0); vis[0][0] = 1;//標記這個點已經走過 bfs(0,0); for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { if(vis[i][j]==0&&map[i][j]==0) { System.out.print(2+" "); } else { System.out.print(map[i][j]+" "); } } System.out.println(); } } }