[kuangbin带你飞]专题一 简单搜索
A - 棋盘问题
暴力搜索
#include <iostream> #include <cstring> using namespace std; int n, k, res; char m[10][10]; bool vis[10][10]; void dfs(int tx, int ty, int dep) { if (dep == k) { res ++; return ; } int i, j; for (i = tx; i < n; ++i) { for (j = (i==tx?ty:0); j < n; ++j) { if (!vis[i][j] && m[i][j] == '#') { bool vv[10][10]; memset(vv, 0, sizeof(vv)); for (int p = 0; p < n; ++p) { for (int q = 0; q < n; ++q) vv[p][q] = vis[p][q]; } for (int p = 0; p < n; ++p) { vis[i][p] = true; vis[p][j] = true; } dfs(i, j, dep+1); for (int p = 0; p < n; ++p) { for (int q = 0; q < n; ++q) vis[p][q] = vv[p][q]; } } } } } int main() { while(cin >> n >> k) { if (n==-1 && k==-1) break; memset(m, 0, sizeof(m)); for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { cin >> m[i][j]; } } res = 0; memset(vis, 0, sizeof(vis)); dfs(0,0,0); cout << res << endl; } return 0; }
B - Dungeon Master
还是暴力
1 #include <iostream> 2 #include <cstring> 3 #include <string> 4 #include <cstdlib> 5 #include <queue> 6 7 using namespace std; 8 9 int l, r, c, res; 10 int sx, sy, sz, ex, ey, ez; 11 string m[31][31]; 12 bool vis[31][31][31], esp; 13 14 struct Node {int x, y, z, rs;}; 15 int dir[6][3] = {-1,0,0,1,0,0,0,-1,0,0,1,0,0,0,-1,0,0,1}; 16 queue<Node> q; 17 18 void bfs() { 19 Node s; 20 s.x = sx, s.y = sy, s.z = sz, s.rs = 0; 21 while(!q.empty()) q.pop(); 22 q.push(s); 23 while(!q.empty()) { 24 Node now = q.front(); q.pop(); 25 Node tmp; 26 for (int i = 0; i < 6; ++i) { 27 int x = now.x+dir[i][0]; 28 int y = now.y+dir[i][1]; 29 int z = now.z+dir[i][2]; 30 if (x >= l || x < 0 || y >= r || y < 0 || z >= c || z < 0) continue; 31 if (vis[z][x][y]) continue; 32 if (m[z][x][y] =='#') continue; 33 vis[z][x][y] = true; 34 tmp.x = x; 35 tmp.y = y; 36 tmp.z = z; 37 tmp.rs = now.rs +1; 38 q.push(tmp); 39 if (x == ex && y == ey && z == ez) { 40 esp = true; 41 res = tmp.rs; 42 return ; 43 } 44 } 45 } 46 return ; 47 } 48 49 int main() { 50 while(cin >> c >> l >> r) { 51 if (!l && !r && !c) break; 52 for (int i = 0; i < c; ++i) { 53 for (int j = 0; j < l; ++j) { 54 cin >> m[i][j]; 55 for (int k = 0; k < m[i][j].size(); ++k) { 56 if (m[i][j][k] == 'S') { 57 sx = j; 58 sy = k; 59 sz = i; 60 } 61 else if (m[i][j][k] == 'E') { 62 ex = j; 63 ey = k; 64 ez = i; 65 } 66 } 67 } 68 } 69 memset(vis, 0, sizeof(vis)); 70 vis[sz][sx][sy] = true; 71 esp = false; 72 bfs(); 73 if (esp) cout << "Escaped in "<<res<< " minute(s)." << endl; 74 else cout << "Trapped!" << endl; 75 } 76 return 0; 77 }
坑

浙公网安备 33010602011771号