微信一笔画完(DFS)

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const double PI = acos(-1.0);
const double eps = 1e-6;
const int MOD = 1e9+7;
const int INF = 0x3f3f3f3f;
const int maxn = 105;
int T,n,cntp,cnt=1,row,cow,flag=0;
int p[maxn][maxn];
int vis[maxn][maxn];
int ans[maxn][maxn];
int dx[] = {1,0,-1,0};
int dy[] = {0,1,0,-1};
int countP();
void dfs(int x, int y);
struct Point {
	int x, y;
	Point(int x=0, int y=0):x(x),y(y){}
	void set(int x, int y) {
		this -> x = x;
		this -> y = y;
	}
}point;
stack<Point> way;

int main() {
	while(1) {
		cnt = 1;
		flag = 0;
		int x, y;
		cin >> row >> cow;
		for (int i = 0; i < maxn; i++)
			for (int j = 0; j < maxn; j++)
				p[i][j] = 1;
		for (int i = 1; i <= row; i++)
			for (int j = 1; j <= cow; j++)
				p[i][j] = 0;
		while (cin >> x >> y && x && y)
			p[x][y] = 1;
		cntp = countP();
		cin >> x >> y;
		dfs(x, y);
	}
	return 0;
}

int countP() {
	int cnt = 0;
	for (int i = 0; i < maxn; i++)
		for (int j = 0; j < maxn; j++)
			if (!p[i][j]) cnt++;
	return cnt;
}

void printWay() {
	int no = cnt;
	while (!way.empty()) {
		ans[way.top().x][way.top().y] = no--;
		way.pop();
	}
	for (int i = 1; i <= row; i++) {
		for (int j = 1; j <= cow; j++) {
			cout << ans[i][j] << "\t";
		}
		cout << endl;
	}
}

void dfs(int x, int y) {
	if (flag || cnt > cntp) {
		return;
	} else if (cnt == cntp) {
		flag = 1;
		point.set(x, y);
		way.push(point);
		printWay();
		return;
	} else {
		for (int i = 0; i < 4; i++) {
			if (!p[x + dx[i]][y + dy[i]] && !vis[x + dx[i]][y + dy[i]] && !flag) {
	            vis[x][y] = 1;
	            cnt++;
				point.set(x, y);
				way.push(point);
	            dfs(x + dx[i], y + dy[i]);
	            vis[x][y] = 0;
	            cnt--;
	            way.pop();
        	}
		}
        return;
	}
}

猜你喜欢

转载自blog.csdn.net/Eimhin_Tang/article/details/83588881