Java implementation of the Blue Bridge Cup analog clearing long grass

Problem Description
  Xiaoming piece of land, he will divide this space into small n rows and m columns, each row and each column length is 1.
  Xiao Ming chose some of them small clearing, planted grass and other small pieces remain open space.
  The grass grows very fast, every month, some of the grass will grow out, if a small piece of grass planted, it will be to own up, down, left and right four small open space expansion, the four small clearing It will become a small piece of grass.
  Please tell Xiao Ming, k months later what place there is grass on the open space.
Input format
  of the first line of input contains two integers n, m.
  Subsequently n rows, each row containing m characters, the open space represents an initial state, there is no spaces between letters. If a decimal point, is represented as open space, if the letters g, represents a kind of grass.
  Next contains an integer k.
Output format
  output n rows, each row containing m characters, k represents a state space months. If a decimal point, is represented as open space, if the letters g, represents the long grass.
Sample input
. 4. 5
.g ...
...
... ... G
...
2
sample output
GGGG.
GGGG.
GGGGG
.ggg.
Reviews agreement with Example scale and
  for evaluation by 30% in Example, 2 <= n, m < = 20.
  For evaluation by 70% in Example, 2 <= n, m < = 100.
  For the evaluation all use cases, 2 <= n, m <= 1000,1 <= k <= 1000.

package 第十三次模拟;

import java.util.Scanner;

public class Demo9草地 {
	public static int[][] bool;
	public static int[] start;
	public static int[] end;
	public static char[][] num  ;
	public static int k = 0, n = 0, m = 0;
	public static int[] x = { 0, 1, 0, -1 };
	public static int[] y = { 1, 0, -1, 0 };

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		n = sc.nextInt();
		m = sc.nextInt();
		  num = new char[n][m];
		for (int i = 0; i < n; i++) {
			String s = sc.next();
			num[i] = s.toCharArray();
		}
		k = sc.nextInt();
		sc.close();
		start = new int[m * n];
		end = new int[m * n];
		int temp = 0;
		bool = new int[n][m];
		for (int i = 0; i < n; i++) {
			for (int j = 0; j < m; j++) {
				if (num[i][j] == 'g') {
					start[temp] = i;
					end[temp++] = j;
				}
				else{
					bool[i][j]=-1;
				}
			}
		}
		for (int i = 0; i < temp; i++) {
			dfs(start[i],end[i],k);
		}
		for (int i = 0; i < n; i++) {
			for (int j = 0; j <m; j++) {
				System.out.print(num[i][j]);
			}
			System.out.println();
		}
	}

	public static void dfs(int xx, int yy, int kk) {
		
		bool[xx][yy]=kk;
		num[xx][yy]='g';
		for (int i = 0; i < 4; i++) {
			int newx = x[i] + xx;
			int newy = y[i] + yy;
			if ( newx >= 0 && newy >= 0 && newx < n && newy < m&&  kk - 1 > bool[newx][newy]) {
				dfs(newx, newy, kk - 1);
			}
		}
	}

}

Released 1472 original articles · won praise 10000 + · views 1.76 million +

Guess you like

Origin blog.csdn.net/a1439775520/article/details/104750331