AOJ - Problem 1174 : Identically Colored Panels Connection

問題文をよく読んで全探索する問題です。同じ色でつながっているパネルはDFSで調べるよいでしょう。
5回までパネルの色を変更できますが5回目は目標の色にするとよいようです。(ソースコードではしていない)

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
typedef vector<vector<int> > Panel;

int dx[4] = {0,-1,1,0};
int dy[4] = {-1,0,0,1};
int w,h,c,ans,color_cnt;

int colorConut(const Panel& a){
	int s=0;
	for(int y=0 ; y < h ; y++ ){
		for(int x=0 ; x < w ; x++ ){
			if( a[y][x] == -1 ) s++;
		}
	}
	return s;
}

void change(Panel& a, int x, int y, int prev_c, int next_c){
	for(int i=0 ; i < 4 ; i++ ){
		int mx = x + dx[i];
		int my = y + dy[i];
		if( mx < 0 || my < 0 || mx >= w || my >= h ) continue;
		if( a[my][mx] == prev_c ){
			a[my][mx] = next_c;
			change( a , mx , my , prev_c , next_c );
		}
	}
}

void solve(const Panel& a, int cnt){
	if( cnt == 6 ){
		Panel b = a;
		b[0][0] = -1;
		change( b , 0 , 0 , c , -1 );
		ans = max( ans , colorConut(b) );
	}else{
		for(int i=1 ; i <= 6 ; i++ ){
			Panel b = a;
			if( a[0][0] == i ) continue;
			b[0][0] = i;
			change( b , 0 , 0 , a[0][0] , i );
			solve( b , cnt+1 );
		}
	}
}

int main(){
	while( cin >> h >> w >> c , h||w||c ){
		Panel a;
		for(int y=0 ; y < h ; y++ ){
			vector<int> v;
			for(int x=0 ; x < w ; x++ ){
				int e;
				cin >> e;
				v.push_back( e );
			}
			a.push_back( v );
		}
		ans = 0;
		solve( a , 1 );
		cout << ans << endl;
	}
}