POJ3050 Hopscotch 窮舉搜索 DFS Map容器再嘗試

Description
The cows play the child’s game of hopscotch in a non-traditional way. Instead of a linear set of numbered boxes into which to hop, the cows create a 5x5 rectilinear grid of digits parallel to the x and y axes.
They then adroitly hop onto any digit in the grid and hop forward, backward, right, or left (never diagonally) to another digit in the grid. They hop again (same rules) to a digit (potentially a digit already visited).
With a total of five intra-grid hops, their hops create a six-digit integer (which might have leading zeroes like 000201).
Determine the count of the number of distinct integers that can be created in this manner.
Input
Lines 1…5: The grid, five integers per line
Output
Line 1: The number of distinct integers that can be constructed
Sample Input
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 2 1
1 1 1 1 1
Sample Output
15
Hint
OUTPUT DETAILS:
111111, 111112, 111121, 111211, 111212, 112111, 112121, 121111, 121112, 121211, 121212, 211111, 211121, 212111, and 212121 can be constructed. No other values are possible.

題目大意:
給定一個5*5的地圖,每個格子上有一個個位數。從一個格子出發(上下左右4個方向),走5步將數字連起來可以構造出一個6位數。問該地圖可以構造出多少個不同的6位數。
解題思路:
本題目的數據量較小,搜索深度也較小,可以對每一個格子都進行DFS,使用Map容器保存已經搜索到的6位數,最終的結果就是Map容器中的元素的個數。

AC代碼

#include<iostream>
#include<map>
#include<string>
using namespace std;
int ans;
map<string, int> que;
char a[6][6];
int mynext[4][2] = { 1,0,-1,0,0,1,0,-1 };
void DFS(int x, int y, int n, string s) {
	s += a[x][y];
	if (n == 0) {
		if (que.find(s) == que.end()) { 
			que[s] = ++ans;
		}
		return;
	}
	for (int i = 0; i < 4; i++) {
		int nx = x + mynext[i][0];
		int ny = y + mynext[i][1];
		if (nx < 1 || nx>5 || ny < 1 || ny>5) continue;
		DFS(nx, ny, n - 1, s);
	}
	return;
}
int main() {
	for (int i = 1; i < 6; i++) {
		for (int j = 1; j < 6; j++) {
			cin >> a[i][j];
		}
	}
	ans = 0;
	for (int i = 1; i < 6; i++) {
		for (int j = 1; j < 6; j++) {
			DFS(i, j, 5, "");
		}
	}
	cout << ans << endl;
	//system("pause");
	return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章