思路:暴力让所有的骆驼和第一只骆驼合并,比如现在是第k只骆驼和第一只合并,广搜找出第k只骆驼如果想和第一只骆驼合并需要走哪一步,然后走一步,并更新所有骆驼的位置。
代码:
#include <bits/stdc++.h> #define pii pair<int, int> #define INF 0x3f3f3f3f using namespace std; const int maxn = 21; char s[maxn][maxn]; int pre[maxn][maxn]; int dx[4] = {0, 1, 0, -1}, dy[4] = {-1, 0, 1, 0}; vector<pii> a; vector<int> ans; int n, m; bool valid(pii x) { return x.first >= 1 && x.first <= n && x.first >= 1 && x.first <= m && s[x.first][x.second] == ‘1‘; } int bfs(pii st, pii ed) { memset(pre, -1, sizeof(pre)); pre[st.first][st.second] = INF; queue<pii> q; q.push(st); while(!q.empty()) { pii tmp = q.front(); q.pop(); if(tmp == ed) { return pre[tmp.first][tmp.second]; } for (int i = 0; i < 4; i++) { int x = tmp.first + dx[i], y = tmp.second + dy[i]; if(!valid(make_pair(x, y)) || pre[x][y] != -1) continue; q.push(make_pair(x, y)); pre[x][y] = (i + 2) % 4; } } } int main() { char mp[4]; mp[0] = ‘L‘, mp[1] = ‘D‘, mp[2] = ‘R‘, mp[3] = ‘U‘; scanf("%d%d", &n, &m); for (int i = 1; i <= n; i++) { scanf("%s", s[i] + 1); for (int j = 1; j <= m; j++) if(s[i][j] == ‘1‘) a.push_back(make_pair(i, j)); } int pos = 1; while(pos < a.size()) { if(a[pos] == a[0]) { pos++; continue; } while(a[pos] != a[0]) { int tmp = bfs(a[0], a[pos]); ans.push_back(tmp); for (int i = 0 ;i < a.size(); i++) { int x = a[i].first + dx[tmp], y = a[i].second + dy[tmp]; if(valid(make_pair(x, y))) a[i] = make_pair(x, y); } } } for (auto x : ans) { printf("%c", mp[x]); } }
原文:https://www.cnblogs.com/pkgunboat/p/10981703.html