机试第9章

TimeTrap Lv2

Catch That Cow(BFS)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
const int MAXN = 1e5;
int step[MAXN], vis[MAXN];

int bfs(int n, int k)
{
queue<int> q;
q.push(n);
step[n] = 0;
vis[n] = 1;
int cur, nxt;
while (!q.empty())
{
cur = q.front();
q.pop();
for (int i = 0; i < 3; ++i)
{
if (i == 0)
nxt = cur + 1;
else if (i == 1)
nxt = cur - 1;
else
nxt = 2 * cur;
if (nxt < 0 || nxt >= MAXN)
continue;
if (!vis[nxt])
{
q.push(nxt);
vis[nxt] = 1;
step[nxt] = step[cur] + 1;
}
if (nxt == k)
return step[nxt];
}
}
return -1;
}

A Knight’s Journey(DFS)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
const int MAXN = 30;
int p, q; // 棋盘参数
bool vis[MAXN][MAXN];
int dir[8][2] = {{-1, -2}, {1, -2}, {-2, -1}, {2, -1}, {-2, 1}, {2, 1}, {-1, 2}, {1, 2}};

bool dfs(int x, int y, int step, string res)
{
if (step == p * q)
{
cout << res << "\n";
return true;
}
for (int i = 0; i < 8; ++i)
{
int nx = x + dir[i][0], ny = y + dir[i][1];
if (nx < 0 || nx >= p || ny < 0 || ny >= q || vis[nx][ny])
continue;
char r = nx + '1', c = ny + 'A';
vis[nx][ny] = 1;
if (dfs(nx, ny, step + 1, res + c + r))
return true;
vis[nx][ny] = 0;
}
return false;
}

八皇后

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
int res = 0, n;
vector<int> tmp;
vector<int> vis(n + 1);

void solve(int cnt, vector<int> &vis)
{
if (cnt == n + 1)
{
for (int i = 0; i < tmp.size(); ++i)
for (int j = 0; j < tmp.size(); ++j)
if (abs(i - j) == abs(tmp[i] - tmp[j]))
return;
res++;
return;
}
for (int i = 1; i <= n; ++i)
if (!vis[i])
{
vis[i] = 1;
tmp.push_back(i);
solve(cnt + 1, vis);
tmp.pop_back();
vis[i] = 0;
}
}
  • 本文标题:机试第9章
  • 本文作者:TimeTrap
  • 创建时间:2023-03-08 12:46:14
  • 本文链接:https://timetrapzz.github.io/2023/03/08/机试第9章/
  • 版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
 评论