[Dfs] B_CodeForce 377_A mazes (connected block problem)

1. Title Description

Pavel likes grid maze. A grid maze is an n × m rectangular maze in which each cell is either blank or a wall. You can walk from one cell to another, as long as both cells are blank and have a common edge.

Pavel draws a grid maze, and all the blank cells contained form a connected area. In other words, you can go from any blank cell to any other blank cell. If Pavel's maze has too few walls, he doesn't like it. He hopes to convert k blank cells into walls, so that all remaining cells can still form a connected area. Please help him achieve this task.

Input

The first line contains three integers n, m, k (1 ≤ n, m ≤ 500, 0 ≤ k <s), where n and m are the height and width of the maze, respectively, and k is the number of walls Pavel wishes to join , And the letter s indicates the number of blank cells in the original maze.

In the next n lines, each line contains m characters. They describe the original maze. If a character in a row is equal to ".", The corresponding cell is blank; if the character is equal to "#", the cell is a wall.

Output

Print n lines, each line containing m characters: a new maze that meets Pavel's needs. Identify the original blank cells that have been converted to walls as "X"; other cells must be left unchanged (that is, "." And "#")

Data Assurance: There is a solution. If there are multiple solutions, you can output any of them.

输入
3 4 2
#..#
..#.
#...
输出
#.X#
X.#.
#...

输入
5 4 5
#...
#.#.
.#..
...#
.#.#
输出
#XXX
#X#.
X#..
...#
.#.#

Second, the solution

Method 1: dfs

  • The question ensures that there must be an answer, which reduces the difficulty to a certain extent, why?
  • Every time we go as far as deep search go elsewhere, so we will go elsewhere throughout the set point X, can guarantee the figure .is still connected.
import java.util.*;
import java.math.*;
import java.io.*;
public class Main{
	static int N, M, k;
	static char[][] grid;
	static boolean[][] vis;
	final static int[][] dir = { {0,1},{0,-1},{1,0},{-1,0} };
	static boolean inArea(int x, int y) {
		return x >= 0 && x < N && y >= 0 && y < M;
	}
	
	static void dfs(int x, int y) {
		for (int k = 0; k < 4; k++) {
			int tx = x + dir[k][0];
			int ty = y + dir[k][1];
			if (!inArea(tx, ty) || grid[tx][ty] != '.' || vis[tx][ty]) {
				continue;
			}
			vis[tx][ty] = true;
			dfs(tx, ty);
		}
		if (k > 0) {
		    grid[x][y] = 'X';
		    k--;
		}
		    
	}
    public static void main(String[] args) throws IOException {  
        Scanner sc = new Scanner(new BufferedInputStream(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
		N = sc.nextInt();
		M = sc.nextInt();
		k = sc.nextInt();
		grid = new char[N][M];
		vis = new boolean[N][M];
		for (int i = 0; i < N; i++) {
			String s = sc.next();
			for (int j = 0; j < M; j++) 
				grid[i][j] = s.charAt(j);
		}
		for (int i = 0; i < N; i++) {
			for (int j = 0; j < M; j++) {
				if (grid[i][j] == '.')
					dfs(i, j);
			}
		}
		for (int i = 0; i < N; i++) {
			for (int j = 0; j < M; j++) {
				System.out.print(grid[x][y]);
			}
			System.out.println();
		}
    }
}

Complexity analysis

  • time complexity: O ( n × m ) O(n × m)
  • Space complexity: O ( n × m ) O(n × m)

Advanced: If the question does not guarantee an answer, how should you deal with this problem?
My approach is: once the mesh BFS, determines whether there is at least the size of a n*m-kcommunication block and communication block marker, and finally traverse the grid again, not marked .as Xcan be.


Method 2: bfs

import java.util.*;
import java.math.*;
import java.io.*;
public class Main{
	static int N, M, k;
	static char[][] grid;
	static boolean[][] vis;
	final static int[][] dir = { {0,1},{0,-1},{1,0},{-1,0} };
	static int cnt, sum, diff;
	static boolean inArea(int x, int y) {
		return x >= 0 && x < N && y >= 0 && y < M;
	}
	static void bfs(int x, int y) {
		Queue<int[]> q = new ArrayDeque<>();
		q.add(new int[] {x, y});
		vis[x][y] = true;
		cnt = 1;
		
		while (!q.isEmpty()) {
			int[] t = q.poll();
			for (int k = 0; k < 4; k++) {
				int tx = t[0] + dir[k][0];
				int ty = t[1] + dir[k][1];
				if (!inArea(tx, ty))
					continue;
				if (grid[tx][ty] == '.' && !vis[tx][ty]) {
			    	if (cnt == diff) {
		    	    	return;
			    	}
    				q.add(new int[]{tx, ty});
    				vis[tx][ty] = true;
				    cnt++;
				}
			}
		}
	}
    public static void main(String[] args) throws IOException {  
        Scanner sc = new Scanner(new BufferedInputStream(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
		N = sc.nextInt();
		M = sc.nextInt();
		k = sc.nextInt();
		grid = new char[N][M];
		vis = new boolean[N][M];
		int sx = -1, sy = -1;
		
		for (int i = 0; i < N; i++) {
			String s = sc.next();
			for (int j = 0; j < M; j++)  {
				grid[i][j] = s.charAt(j);
				if (grid[i][j] == '.') {
					sum++;
					sx = i; sy = j;
				}
			}
		}
		if (sx == -1 && sy == -1) {
			System.out.println(-1);
			return;
		}
		diff = sum - k;
		bfs(sx, sy);
		for (int i = 0; i < N; i++) {
			for (int j = 0; j < M; j++) {
				if (vis[i][j] && grid[i][j] == '.') {
					System.out.print('.');
				} else if (!vis[i][j] && grid[i][j] == '.') {
					System.out.print('X');
				} else {
					System.out.print('#');
				}
			}
			System.out.println();
		}
    }
}

Complexity analysis

  • time complexity: O ( n × m ) O(n × m)
  • Space complexity: O ( n × m ) O(n × m)
Published 714 original articles · praised 199 · 50,000+ views

Guess you like

Origin blog.csdn.net/qq_43539599/article/details/105602743