Table of contents
Previous article in the same series - Portal
This chapter includes maze problems, Flood Fill flood irrigation problems, chessboard problems
How to indicate whether a point has been passed
Question 2: [USACO10OCT] Lake Counting S
What conditions must be met in the location that needs to be irrigated
Question 3: Chessboard Problem
Chessboard problem - two-dimensional version of the full arrangement model
Guaranteed to place at most one pawn in each row and column
Pieces can only be placed in the '#' area, not in the '.' area
Question 4: [NOIP2001 Improvement Group] Number Division
dfs combined template - upgraded version (elements can be selected repeatedly)
Previous article in the same series - Portal
[Blue Bridge Cup] DFS Depth Priority Practice Questions - Basic Entry Template (1)_Xiaolu Xianchong's Blog-CSDN Blog The first question: recursive realization of exponential enumeration, the second question: full permutation question, the third question: combination The output of
https://blog.csdn.net/weixin_61082895/article/details/129874100?spm=1001.2014.3001.5501
[Blue Bridge Cup] The correct way to get started with DFS - the basic template (2 ) Popularization Group] Martian Question 4: [NOIP2008 Improvement Group] Matchstick Equation, Question 5: PERKET, Question 6: Strange Elevator
https://blog.csdn.net/weixin_61082895/article/details/129895135? spm=1001.2014.3001.5501
Big guy teaching video, very detailed!
This chapter includes maze problem, Flood Fill flood irrigation problem, chessboard problem
Question 1: Getting Started
topic description
Not everyone can enter Peach Blossom Island, Huang Yaoshi hates people who are as stupid as Guo Jing the most. Therefore, he built a small path at the only entrance to Peach Blossom Island, which was entirely paved with square tiles. Some tiles can be stepped on, we think it is safe, and some tiles will emit deadly poisonous gas when you step on them, then you will die, we think it is not safe. You can only walk from a safe tile to any of the four adjacent tiles, but it must also be safe.
Since you are Huang Rong's friend, she told you in advance which bricks are safe and which bricks are not safe, and she will guide you to fly to the first brick (the first brick may be in any safe position), now she The secret to tell you to enter Peach Blossom Island is: if you can walk through the most tiles without dying, then the gate of Peach Blossom Island will be opened automatically, and you can fly directly into the gate from your current position.
Note: Tiles can be walked over repeatedly, but not counted repeatedly.
input format
The first line contains two positive integers W and H, representing the width and length of the path, respectively.
The following H row is a H×W character matrix. Each character represents a tile. Among them,
.
the safe brick#
represents the unsafe brick and@
represents the first brick.output format
Output a line, including only one number, that is, the maximum number of bricks you can walk safely from the first brick (including the first brick).
Input and output samples
enter
11 9 .#......... .#.#######. .#.#.....#. .#.#.###.#. .#.#..@#.#. .#.#####.#. .#.......#. .#########. ...........output #1 copy
59Instructions/Tips
Data Size and Conventions
For all test points, it is guaranteed that 1≤W, H≤20.
maze problem
topic analysis
difficulty
How to save the map
static char arr[][];//maphow to go, how to turn
static int dx[] = {-1, 0, 1, 0};//top right bottom left static int dy[] = {0, 1, 0, -1};- What is the boundary, how to go'.'not go'#'
if (a < 0 || a >= n || b < 0 || b >= m) continue; if (arr[a][b] != '.') continue;How to indicate whether a point has been passed
static Boolean st[][];//Record whether the tile has goneif (st[a][b]) continue;//This point has been passed
topic code
import java.util.Scanner; public class 入门_dfs { static int n, m, res; static Boolean st[][];//记录瓷砖走没走过 static char arr[][];//地图 static int dx[] = {-1, 0, 1, 0};//上右下左 static int dy[] = {0, 1, 0, -1}; public static void main(String[] args) { arr = new char[25][25]; st = new Boolean[25][25]; Scanner sca = new Scanner(System.in); m = sca.nextInt();//列 n = sca.nextInt();//行 sca.nextLine(); for (int i = 0; i < n; i++) {//输入 arr[i] = sca.next().toCharArray(); } int a = 0, b = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { st[i][j] = false; if (arr[i][j] == '@') { st[i][j] = true; a = i; b = j; } } } dfs(a,b); res++; System.out.println(res); } static void dfs(int x, int y) {//当前访问的坐标是 x,y for (int i = 0; i < 4; i++) {//拐弯 共4个方向 int a = x + dx[i], b = y + dy[i];//顺序为上右下左 if (a < 0 || a >= n || b < 0 || b >= m) continue; if (arr[a][b] != '.') continue; if (st[a][b]) continue;//这个点被走过 //走(a, b)这个点 st[a][b] = true; res++; dfs(a, b);//搜索 } } }
Question 2: [USACO10OCT] Lake Counting S
topic description
Due to the recent rainfall, rainwater has collected in different places on Farmer John's field. We represent it with an N×M (1≤N≤100, 1≤M≤100) grid graph. Each grid contains either water (
W
) or dry land (.
). A mesh is connected to its surrounding eight meshes, and a group of connected meshes is considered a puddle. John is trying to figure out how many puddles his field has formed. Given a schematic diagram of John's field, determine how many puddles are in it.Enter line 1: two integers separated by a space: N and M.
Lines 2 to N+1: M characters per line, each character is
W
or.
, which represent a row in the grid diagram. There are no spaces between characters.Output a line indicating the number of puddles.
Input and output samples
Type #1 to copy
10 12 W........WW. .WWW.....WWW ....WW...WW. .........WW. .........W.. ..W......W.. .W.W.....WW. W.W.W.....W. .W.W......W. ..W.......W.output #1 copy
3
flood irrigation problem
topic analysis
difficulty
How to save the map
static char mp[][] = new char[150][150];//maphow to go, how to turn
static int dx[] = {1, 1, 1, 0, 0, -1, -1, -1};//8连通 static int dy[] = {-1, 0, 1, 1, -1, 1, 0, -1};- what is the boundary
if (a < 0 || a >= n || b < 0 || b >= m) continue;//Change a directionWhat conditions must be met in the location that needs to be irrigated
if (mp[i][j] == 'W' && !st[i][j]) {//灌溉 dfs(i, j); res++;if (mp[a][b] != 'W') continue;//This position cannot be irrigated, change the direction if (st[a][b]) continue;//This position has been irrigated, change it direction
topic code
import java.util.Scanner; public class 洪水灌溉问题_dfs { static int n, m, res; static char mp[][] = new char[150][150];//地图 static Boolean st[][] = new Boolean[150][150];//表示每个位置有没有被灌溉过 static int dx[] = {1, 1, 1, 0, 0, -1, -1, -1};//8连通 static int dy[] = {-1, 0, 1, 1, -1, 1, 0, -1}; public static void main(String[] args) { Scanner sca = new Scanner(System.in); n = sca.nextInt(); m = sca.nextInt(); sca.nextLine(); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { st[i][j] = false; } } for (int i = 0; i < n; i++) { mp[i] = sca.next().toCharArray(); } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (mp[i][j] == 'W' && !st[i][j]) { dfs(i, j); res++; } } } System.out.println(res); } static void dfs(int x, int y) {//给符合条件的位置浇水 for (int i = 0; i < 8; i++) {//8连通 int a = x + dx[i], b = y + dy[i]; if (a < 0 || a >= n || b < 0 || b >= m) continue;//换一个方向 if (mp[a][b] != 'W') continue;//这个位置不能灌溉,换一个方向 if (st[a][b]) continue;//这个位置被灌溉过了,换一个方向 st[a][b] = true; dfs(a, b); } } }
Question 3: Chessboard Problem
topic description
There is no difference between chess pieces placed on a chessboard of a given shape (the shape may be irregular).
It is required that any two chess pieces cannot be placed in the same row or column of the chessboard when placing them. Please program to solve the number C of all feasible arrangements for placing k pieces on a chessboard of a given shape and size.
input format
The input contains multiple sets of test data.
The first line of each set of data is two positive integers n, k, separated by a space, indicating that the chessboard will be described in an n∗n matrix and the number of chess pieces placed. When
-1 -1
is indicates the end of the input.The next n lines describe the shape of the checkerboard: each line has n characters, which
#
represent the checkerboard area and.
represent the blank area (the data guarantees that there will be no redundant blank rows or blank columns).output format
For each set of data, a line of output is given, and the number of schemes placed in the output is C (data guarantee C<231).
data range
n≤8,k≤n
Input sample:
2 1 #. .# 4 4 ...# ..#. .#.. #... -1 -1
Sample output:
2 1
Chessboard problem - two-dimensional version of the full arrangement model
topic analysis
difficulty
Guaranteed to place at most one pawn in each row and column
Enumerate each column of each row to judge whether there are chess pieces in each column of the current rowstatic void dfs(int x, int count) //x means to enumerate the current row, count means how many chess pieces are placedfor (int i = 0; i < n; i++) //enumeration column if (!st[i] && map[x][i] == '#') //when there is no piece in this columnPieces can only be placed in the '#' area, not in the '.' area
Pay attention to a situation: when the next line cannot be accessed, it needs to be accessed forcibly. In this case, the second line will never be accessed (deduce by yourself)
2 1 #. .#
dfs(x+1,count);//Forcibly access when the next line cannot be accessed
topic code
import java.util.Scanner; public class 棋盘问题_dfs { static int n, k, res; static boolean st[] = new boolean[10];//用来判断每一列是否放了元素 static char[][] map = new char[10][10];//地图 public static void main(String[] args) { Scanner sca = new Scanner(System.in); while (true) {//输入 n = sca.nextInt(); k = sca.nextInt(); if (n == -1 && k == -1) break; sca.nextLine(); for (int i = 0; i < n; i++) { map[i] = sca.next().toCharArray(); } res = 0; dfs(0, 0); System.out.println(res); } } static void dfs(int x, int count) {//x表示枚举当前行,count表示放了几个棋子 if (count == k) { res++; return; } if (x >= n) return; for (int i = 0; i < n; i++) {//枚举列 if (!st[i] && map[x][i] == '#') {//当这一列没有放棋子时 st[i] = true; dfs(x + 1, count + 1); st[i] = false;//回溯恢复现场 } } dfs(x+1,count);//当访问不到下一行强行访问 } }
Question 4: [NOIP2001 Improvement Group] Number Division
topic description
Divide the integer n into k parts, and each part cannot be empty, and any two schemes are different (regardless of the order).
For example: n=7, k=3, the following three divisions are considered to be the same.
1,1,51,1,5;
1,5,11,5,1;
5,1,15,1,1.Ask how many different divisions there are.
input format
n,k (6<n≤200,2≤k≤6)
output format
1 integer, that is, different divisions.
Input and output samples
Type #1 to copy
7 3output #1 copy
4Instructions/Tips
The four divisions are:
1,1,51,1,5;
1,2,41,2,4;
1,3,31,3,3;
2,2,32,2,3.
topic analysis
dfs combined template - upgraded version (elements can be selected repeatedly)
topic code
import java.util.Scanner; public class 数的划分_dfs { static int n, k, res; static int arr[] = new int[250];//存答案 这道题不需要输出答案 public static void main(String[] args) { Scanner sca = new Scanner(System.in); n = sca.nextInt(); k = sca.nextInt(); dfs(1, 0, 1); System.out.println(res); } static void dfs(int x, int sum, int start) {//x:枚举的位置 sum:每次枚举到当前位置的和 start每次从几开始枚举 if (sum > n) return; if (x > k) { if (sum == n) { res++; } return; } for (int i = start; i <= n; i++) { arr[i] = i; dfs(x + 1, sum + i, i);//注意这里每一个位置在枚举的时候是从i开始的不要写成start arr[i] = 0;//恢复现场 } } }