UVa 1103

好题。百思不得其解如何利用DFS获取一个图中的圈数,参考了一些博客,恍然大悟,思想很巧妙,利用连通图,将图分开几个部分,边缘就成了一部分,圈又成了一部分,只需要记录接壤的圈即可。

题目主要想教会coder的,就是抓住特征量的想法。

宁可一思进,莫在一思停。写代码原来就和打游戏一样,耐得住寂寞和迈出舒适区的天性会导致的抗拒,摆脱生活因为算法对自己脑子越来越追求高刺激的倾向。

#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
#include <unordered_map>
#include <cstdio>
#include <cstring>
using namespace std;

const int maxh= 205;
const int maxw= 55;
const char code[]= "WAKJSD"; // A-1 J-3 D-5 S-4 W-0 K-2

vector<string> pic;
unordered_map<char, string> h2d={
	{'0', "0000"}, {'1', "0001"}, {'2', "0010"}, {'3', "0011"},
	{'4', "0100"}, {'5', "0101"}, {'6', "0110"}, {'7', "0111"},
	{'8', "1000"}, {'9', "1001"}, {'a', "1010"}, {'b', "1011"},
	{'c', "1100"}, {'d', "1101"}, {'e', "1110"}, {'f', "1111"}
};
int dd[4][2]= {
	{-1, 0}, {1, 0}, {0, -1}, {0, 1}
};
int H, W;

void Init()
{
	pic.resize(H+2);
	W<<= 2;
	pic.back()= pic.front()= string(2+W, '0');
}
void dfs(int x, int y, char clr, int &cnt)
{
	pic[x][y]= char(clr+2);
	for (int i= 0; i< 4; ++i){
		int nx= x+dd[i][0], ny= y+dd[i][1];
		if (0<= nx && H+1>= nx && 0<= ny && 1+W>= ny){
			if ('1'== clr && '0'== pic[nx][ny]){
				dfs(nx, ny, '0', ++cnt);
			}
			if (clr== pic[nx][ny]){
				dfs(nx, ny, clr, cnt);
			}
		}
	}

}

int main(int argc, char const *argv[])
{
	int kase= 0;

	while (2== scanf("%d %d%*c", &H, &W) && H){
		Init();
		for (int i= 1; i<= H; ++i){
			pic[i]= "0";
			string ts;
			getline(cin, ts);
			for (char c : ts){
				pic[i]+= h2d[c];
			}
			pic[i]+= "0";
		}

		int cnt= 0;
		string lts="";
		dfs(0, 0, '0', cnt);

		for (int i= 1; i<= H; ++i){
			for (int j= 1; j<= W; ++j){
				if ('1'== pic[i][j]){
					cnt= 0;
					dfs(i, j, '1', cnt);
					lts+= code[cnt];
				}
			}
		}

		sort(lts.begin(), lts.end());
		printf("Case %d: %s\n", ++kase, lts.c_str());
	}
	return 0;
}
posted @ 2021-01-19 16:55  IdiotNe  阅读(78)  评论(0编辑  收藏  举报