POJ 1414

找找手感一道題,有些類似於uva此前做過的一道判斷照片字母形狀的題,利用DFS求聯通分量。

這裏要格外注意邊緣碰到0的情況的討論,當遍歷一個連通分量時,整個連通分量必須遍歷完再推出,不可以分幾次遍歷同一連通分量,這是DEBUG好久得出的教訓

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

const int maxn= 15;
const int INF= 0x3f3f3f3f;

int n, c;
int bd[maxn][maxn];
bool vis[maxn][maxn];
int step[6][2]= {
	{-1, -1}, {-1, 0}, {0, -1}, {0, 1}, {1, 0}, {1, 1}
};

int dfs(int x, int y)
{
	vis[x][y]= 1;
	if (!bd[x][y]){
		return 0;
	}
	int sm= 1;
	int flag= 0;

	for (int i= 0; i< 6; ++i){
		int nx= x+step[i][0], ny= y+step[i][1];
		if (!bd[nx][ny]){
			flag= 1;
		}
		if (bd[x][y]!= bd[nx][ny]){
			continue;
		}
		else if (!vis[nx][ny]){
			int tp= dfs(nx, ny);
			if (!tp){
				flag= 1;
			}
			sm+= tp;
		}
	}

	return flag ? 0 : sm;
}

int main(int argc, char const *argv[])
{
	memset(bd, -1, sizeof(bd));

	while (2== scanf("%d %d", &n, &c) && n){
		int ans= -INF;
		for (int i= 1; i<= n; ++i){
			for (int j= 1; j<= i; ++j){
				scanf("%d", bd[i]+j);
			}
		}
		memset(bd+n+1, -1, sizeof(bd[0]));

		for (int i= 1; i<= n; ++i){
			for (int j= 1; j<= i; ++j){
				if (!bd[i][j]){
					int tmp= 0;
					memset(vis, 0, sizeof(vis));
					bd[i][j]= c;

					for (int x= 1; x<= n; ++x){
						for (int y= 1; y<= x; ++y){
							if (vis[x][y]){
								continue;
							}
							if (c== bd[x][y]){
								tmp-= dfs(x, y);
							}
							else{
								tmp+= dfs(x, y);
							}
						}
					}
					bd[i][j]= 0;
					ans= max(ans, tmp);
				}
			}
		}
		printf("%d\n", ans);
	}
	return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章