杭州电子科技大学上机题——切模板
题目描述:
有一个MN的材料和一个ST的模板,从材料中切除模板,求最大能切出来的模板数量。
输入:
第一行 M N
下面的M行N列:材料的具体内容
第MM+2行: S T
下面的S行T列:模板材料的具体内容
Sample input:
3 4
a b c d
c d a b
a c c d
2 2
a b
c d
Sample out:
2
算法思想 使用dfs
#include "iostream"
using namespace std;
char material[1024][1024] = { 0 };
int m, n;
char temp[1024][1024] = { 0 };
int s, t;
bool visited[1024][1024] = { 0 };
int maxcnt = 0;
bool check(int x, int y) {
for (int i = 0; i < s; i++)
for (int j = 0; j < t; j++)
if (material[x + i][y + j] != temp[i][j])
return false;
return true;
}
void cut(int x, int y) {
for (int i = 0; i < s; i++) {
for (int j = 0; j < t; j++) {
visited[x + i][y + j] = 1;
}
}
}
void nocut(int x, int y) {
for (int i = 0; i < s; i++) {
for (int j = 0; j < t; j++) {
visited[x + i][y + j] = 0;
}
}
}
void DFS(int x, int y, int cnt) {
if (maxcnt < cnt) {
maxcnt = cnt;
}
if (x >= m - s + 1)return;
if (y >= n - t + 1) {
DFS(x + 1, 0, cnt);
}
else {
if (visited[x][y] == false) {
if (check(x, y)) {
cut(x, y);
DFS(x, y + t, cnt + 1);
}
nocut(x, y);
DFS(x, y + 1, cnt);
}
else {
DFS(x, y + 1, cnt);
}
}
}
int main(void) {
cin >> m >> n;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
cin >> material[i][j];
}
}
cin >> s >> t;
for (int i = 0; i < s; i++) {
for (int j = 0; j < t; j++) {
cin >> temp[i][j];
}
}
DFS(0, 0, 0);
cout << maxcnt << endl;
return 0;
}
//3 4
//a b c d
//c d a b
//a c c d
//2 2
//a b c d