好久不写代码了出来写个dfs。
/* * Author: stormdpzh * Created Time: 2013/5/2 14:15:51 * File Name: poj_1683.cpp */ #include <iostream> #include <cstdio> #include <sstream> #include <cstring> #include <string> #include <cmath> #include <vector> #include <queue> #include <stack> #include <map> #include <set> #include <list> #include <algorithm> #include <functional> #define sz(v) ((int)(v).size()) #define rep(i, n) for(int i = 0; i < n; i++) #define repf(i, a, b) for(int i = a; i <= b; i++) #define repd(i, a, b) for(int i = a; i >= b; i--) #define out(n) printf("%d\n", n) #define mset(a, b) memset(a, b, sizeof(a)) using namespace std; typedef long long lint; const int INF = 1 << 30; const int MaxN = 100005; struct Node { int p; char c; Node() {} Node(int _p, char _c) : p(_p), c(_c) {} }; bool vis[10][10]; bool cT[50][50]; bool nT[50][50]; int n, m; char mp[10][10]; vector<Node> vec[10]; bool check(vector<Node> v) { int len = sz(v); rep(i, len) { repf(j, i + 1, len - 1) { if(nT[v[i].p][v[j].p]) return false; } } if(len == n) { rep(i, len) { int u = v[i].p; rep(j, n * m) { if(cT[u][j]) { bool f = false; rep(k, len) { if(v[k].p == j) { f = true; break; } } if(!f) return false; } } } } return true; } bool gao(int r, int c) { if(r >= n) return true; if(c >= m) return true; rep(i, m) { if(!vis[r][i]) { vec[c].push_back(Node(r * m + i, mp[r][i])); vis[r][i] = true; if(check(vec[c])) { bool f = gao(r + 1, c); if(f) { if(r == n - 1) { bool f = gao(0, c + 1); if(f) return true; else { vec[c].pop_back(); vis[r][i] = false; } } else return true; } else { vec[c].pop_back(); vis[r][i] = false; } } else { vec[c].pop_back(); vis[r][i] = false; } } } return false; } int main() { int t; scanf("%d", &t); bool f = false; while(t--) { if(f) puts(""); scanf("%d%d", &n, &m); rep(i, n) scanf("%s", mp[i]); mset(nT, false); mset(cT, false); int x1, y1, x2, y2; char ch; while(5 == scanf("%d%d %c %d%d", &x1, &y1, &ch, &x2, &y2)) { if(x1 == 0 && y1 == 0 && x2 == 0 && y2 == 0 && ch == 'R') break; int xx1 = (x1 - 1) * m + y1 - 1; int yy1 = (x2 - 1) * m + y2 - 1; if(ch == 'R') cT[xx1][yy1] = cT[yy1][xx1] = true; else nT[xx1][yy1] = nT[yy1][xx1] = true; } rep(i, 10) vec[i].clear(); mset(vis, false); gao(0, 0); rep(i, m) { rep(j, n) { printf("%c", vec[i][j].c); } puts(""); } f = true; } return 0; }