例题1.14 填充正方形 UVa11520

1.题目描述:点击打开链接

2.解题思路:本题要求字典序最小,由于n的范围比较小,直接尝试按照字典序填写每个格子即可。

3.代码:

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

#define N 10+5
char g[N][N];
int dx[] = { 1, -1, 0, 0 };
int dy[] = { 0, 0, 1, -1 };
int vis[26];
int n;
bool is_inside(int r, int c)
{
	if (r < 0 || r >= n || c < 0 || c >= n)return false;
	return true;
}
void dfs(int cur)
{
	if (cur == n*n)
	{
		for (int i = 0; i < n;i++)
		for (int j = 0; j < n; j++)
			printf("%c%s", g[i][j], j == n - 1 ? "\n" : "");
		return;
	}
	int r = cur / n, c = cur%n;
	if (g[r][c] == '.')
	{
		memset(vis, 0, sizeof(vis));
		for (int d = 0; d < 4; d++)
		{
			int nx = r + dx[d], ny = c + dy[d];
			if (is_inside(nx, ny) && isupper(g[nx][ny]))//找周围的字母
				vis[g[nx][ny] - 'A'] = 1;
		}
		for (int i = 0; i<26; i++)//找字典序最小的字母
		if (!vis[i]){ g[r][c] = i + 'A'; break; }
	}
	dfs(cur + 1);
}
int main()
{
	//freopen("t.txt", "r", stdin);
	int T;
	cin >> T;
	for (int rnd = 1; rnd <= T; rnd++)
	{
		scanf("%d", &n);
		for (int i = 0; i < n; i++)
			scanf("%s", g[i]);
		printf("Case %d:\n",rnd);
		dfs(0);
	}
	return 0;
}

你可能感兴趣的:(搜索)