#include <iostream>
#include <istream>
#include <sstream>
#include <vector>
#include <stack>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <queue>
#include <cstring>
#include <unordered_map>
#include <unordered_set>
#include <algorithm>
#include <numeric>
#include <chrono>
#include <ctime>
#include <cmath>
#include <cctype>
#include <string>
#include <cstdio>
#include <iomanip>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <functional>
#include <iterator>
using namespace std;
const int Row = 7, Col = 8, Dir[2][2] = { { 1, 0 }, {0,1} };
int matrix[Row*Col], result[Row][Col], id[255] = {0}, vis[255], cnt = 0,cid;
int GetData(int r, int c){
return matrix[r * Col + c];
}
int GetID(char a, char b){
if (a > b) swap(a, b);
return id[(a << 4)|b];
}
bool GetNext(int &x, int &y){
while (y < Col){
if (!result[x][y]) return true;
y++;
if (y == Col){
x++; y = 0;
if (x == Row) return false;
}
}
return false;
}
void OutPrint()
{
cout << "Layout #" << cid << ":" << endl << endl;
for (int i = 0; i < Row; i++){
for (int j = 0; j < Col; j++){
cout << setw(4) << GetData(i,j);
}
cout << endl;
}
cout << endl;
}
void OutPrint2()
{
for (int i = 0; i < Row; i++){
for (int j = 0; j < Col; j++){
cout << setw(4) << result[i][j];
}
cout << endl;
}
cout << endl;
}
void dfs(int x, int y,int c){
if (c == 28){
cnt++;
OutPrint2();
return;
}
if (!GetNext(x, y)) return;
for (int i = 0; i < 2; i++){
int nx = x + Dir[i][0];
int ny = y + Dir[i][1];
if (nx >= Row || ny >= Col || result[nx][ny]) continue;
int t = GetID(GetData(x, y), GetData(nx, ny));
if (vis[t]) continue;
result[x][y] = t;
result[nx][ny] = t;
vis[t] = 1;
dfs(x, y, c + 1);
result[x][y] = 0;
result[nx][ny] = 0;
vis[t] = 0;
}
}
int main()
{
int a = 0;
for (int i = 0; i <= 6; i++){
for (int j = i; j <= 6; j++){
id[(i << 4) | j] = ++a;
}
}
a = cid = 0;
while (cin >> matrix[ a++ ]){
if (a < 56) continue;
a = cnt = 0;
memset(result, 0, sizeof(result));
memset(vis, 0, sizeof(vis));
if (cid++) cout << endl << endl << endl;
OutPrint();
cout << "Maps resulting from layout #" << cid << " are:" << endl << endl;
dfs(0, 0,0);
cout << "There are " << cnt << " solution(s) for layout #" << cid << "." << endl;
}
return 0;
}
习题7-3(uva-211)
最新推荐文章于 2023-11-14 07:00:00 发布
该博客探讨了一个C++程序,它使用深度优先搜索(DFS)算法来解决特定的矩阵排列问题。程序涉及了多种数据结构如栈、队列、图、字符串等,并通过DFS遍历所有可能的排列,寻找符合条件的解决方案。文章展示了如何处理矩阵数据,以及如何通过递归实现搜索。
266

被折叠的 条评论
为什么被折叠?



