Overlapping Squares UVA - 12113

还是一道考察搜索的题目,将抽象出来的正方形向大的正方形中逐步放置,在放置的时候要注意计算好小正方形的位置信息,同时要对放置的小正方形的个数进行计数,在放置每一个小正方形之前要判断当前的大正方形的状态是否与目标的状态一致,如果一致,那么就直接返回true即可,如果不一致就继续递归推断,同时在代码中利用一个visit数组来避免小正方形的重复放置,具体实现见如下代码:

#include<iostream>
#include<vector>
#include<string>
#include<set>
#include<stack>
#include<queue>
#include<map>
#include<algorithm>
#include<cmath>
#include<iomanip>
#include<cstring>
#include<sstream>
#include<cstdio>
#include<deque>
#include<functional>
using namespace std;

int Case;
char data[5][15],cur[5][9];
bool visit[9];

bool judge(){
	for (int i = 0; i < 5; i++){
		for (int j = 0; j < 9; j++){
			if (data[i][j] != cur[i][j]) return false;
		}
	}
	return true;
}

bool dfs(int step){
	if (judge()) return true;
	if (step >= 6) return false;
	char temp[5][9];
	for (int m = 0; m < 5; m++){
		for (int n = 0; n < 9; n++){
			temp[m][n] = cur[m][n];
		}
	}
	for (int i = 0; i < 9; i++){
		int row = i / 3 + 1, col = 2 * (i % 3) + 1;
		if (visit[i]) continue;
		visit[i] = true;
		cur[row][col - 1] = cur[row + 1][col - 1] = cur[row][col + 3] = cur[row + 1][col + 3] = '|';
		cur[row - 1][col] = cur[row - 1][col + 2] = cur[row+1][col] = cur[row+1][col + 2] = '_';
		cur[row][col] = cur[row][col + 1] = cur[row][col + 2] = cur[row + 1][col + 1] = ' ';
		if (dfs(step + 1)) return true;
		visit[i] = false;
		for (int m = 0; m < 5; m++){
			for (int n = 0; n < 9; n++){
				cur[m][n] = temp[m][n];
			}
		}
	}
	return false;
}

int main(){
	Case = 0;
	while (true){
		Case++;
		memset(visit, 0, sizeof(visit));
		for (int i = 0; i < 5; i++){
			gets(data[i]);
			if (data[i][0] == '0') return 0;
		}
		for (int i = 0; i < 5; i++){
			for (int j = 0; j < 9; j++){
				cur[i][j] = ' ';
			}
		}
		cout << "Case " << Case << ":";
		if (dfs(0)) cout << " Yes\n";
		else cout << " No\n";
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值