int T, n, m, flag; int vis[N][N]; char a[N][N]; vector<pair<int, int>> start, ended; int dx[] = {0, 0, 0, 1, -1}; int dy[] = {0, 1, -1, 0, 0};
voidinit(){ for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { vis[i][j] = 0; } } }
voidbfs1(int sx, int sy){ init(); queue<tuple<int, int>> q; q.push({sx, sy}); vis[sx][sy] = 1; while (!q.empty()) { auto [x, y] = q.front(); if (x == n && y == m) { flag = 1; return; } q.pop(); for (int i = 1; i <= 4; i++) { int tx = x + dx[i]; int ty = y + dy[i]; if (tx >= 1 && tx <= n && ty >= 1 && ty <= m && !vis[tx][ty]) { if (!vis[tx][ty] && a[tx][ty] != '#') { vis[tx][ty] = 1; q.push({tx, ty}); } if (a[tx][ty] == '#') { start.push_back({tx, ty}); } } } } }
voidbfs2(int sx, int sy){ init(); queue<tuple<int, int>> q; q.push({sx, sy}); vis[sx][sy] = 1; while (!q.empty()) { auto [x, y] = q.front(); q.pop(); for (int i = 1; i <= 4; i++) { int tx = x + dx[i]; int ty = y + dy[i]; if (tx >= 1 && tx <= n && ty >= 1 && ty <= m) { if (!vis[tx][ty] && a[tx][ty] != '#') { vis[tx][ty] = 1; q.push({tx, ty}); } if (a[tx][ty] == '#') { ended.push_back({tx, ty}); } } } } }
voidbfs3(){ init(); queue<tuple<int, int, int>> q; for (auto [x, y] : start) q.push({x, y, 1}); while (!q.empty()) { auto [x, y, step] = q.front(); q.pop(); if (vis[x][y]) continue; vis[x][y] = step; for (int i = 1; i <= 4; i++) { int tx = x + dx[i]; int ty = y + dy[i]; if (tx >= 1 && tx <= n && ty >= 1 && ty <= m) { q.push({tx, ty, step + 1}); } } } int ans = 1e9; for (auto [x, y] : ended) ans = min(ans, vis[x][y]); cout << ans << '\n'; }
voidsolve(){ start.clear(), ended.clear(); flag = 0; cin >> n >> m; for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { cin >> a[i][j]; } } bfs1(1, 1); if (flag) { cout << "0\n"; return; } bfs2(n, m); if (start.empty()) { cout << "0\n"; return; } bfs3(); }
int n, m; map<char, int> mp; bool vis[60][60]; char a[60][60]; int dx[] = {0, 0, 0, 1, -1}; int dy[] = {0, 1, -1, 0, 0};
booldfs(int x, int y, char k, int prex, int prey){ vis[x][y] = 1; for (int i = 1; i <= 4; i++) { int tx = x + dx[i]; int ty = y + dy[i]; if (tx == prex && ty == prey) continue; if (vis[tx][ty] && a[tx][ty] == k) returntrue; if (tx >= 1 && tx <= n && ty >= 1 && ty <= m && !vis[tx][ty] && a[tx][ty] == k) { if (dfs(tx, ty, k, x, y)) returntrue; } } returnfalse; }
intmain(){ cin >> n >> m; for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) cin >> a[i][j], mp[a[i][j]]++; for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { if (vis[i][j]) continue; if (mp[a[i][j]] < 4) continue; if (dfs(i, j, a[i][j], -1, -1)) { cout << "Yes"; return0; } } } cout << "No"; return0; }
intgcd(int a, int b){ return !b ? a : gcd(b, a % b); }
voiddfs(int a, int b, int k){ if (k > 26) return; if (k >= ans) return; if (a == 0 && b == 0) { ans = min(ans, k); return; } if (a > 0) dfs(a - gcd(a, b), b, k + 1); if (b > 0) dfs(a, b - gcd(a, b), k + 1); }
voidsolve(){ ans = 30; int a, b; cin >> a >> b; dfs(a, b, 0); cout << ans << '\n'; }