week 4
题1
P1605迷宫
dfs,额,题里面要注意的是数组要开大点。不然 2 8 10会wa
然后是一些关于dfs的不知道对不对的理解
1.每调用一次dfs,相当于多画了一个分支,
2.每搜索到一个节点,如果这个节点还能往下搜,dfs会再调用函数往深处搜
3.如果是坐标系里用dfs,要打标记表示走过
#include<bits/stdc++.h>
using namespace std;
int n, m, t;
int ori[5][5] = { 0 };
int again[5][5] = { 0 };
//0 空 1起点 2终点 3障碍
int num = 0;
void dfs(int x, int y) {
if (x < 0 || x>n-1 || y < 0 || y>m-1) {
return;
}
if (again[x][y] == 1||ori[x][y]==3) {
return;
}
if (ori[x][y] == 2) {
num++;
return;
}
again[x][y] = 1;
dfs(x + 1, y);
dfs(x - 1, y);
dfs(x,y + 1);
dfs(x, y - 1);
again[x][y] = 0;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin >> n >> m >> t;
int t1, t2, t3, t4;
cin >> t1 >> t2 >> t3 >> t4;
ori[t1-1][t2-1] = 1;
ori[t3-1][t4-1] = 2;
for (int i = 0; i < t; i++) {
int t10, t20;
cin >> t10 >> t20;
ori[t10-1][t20-1] = 3;
}
dfs(t1-1, t2-1);
cout << num;
}
题2
P1443 马的遍历
如果用bfs搜最短路径,可以定义个step,起点的step=0,之后在把新点往队列里push的后面加个step[新点]=step[旧点]+1;
#include <bits/stdc++.h>
using namespace std;
struct add {
int x;
int y;
};
queue <add> temp;
int n, m, sx, sy;
int ori[500][500];
int again[500][500];
int fangx(int x, int i) {
switch (i)
{
case 0:
return x + 1;
break;
case 1:
return x + 2;
break;
case 2:
return x + 2;
break;
case 3:
return x + 1;
break;
case 4:
return x - 1;
break;
case 5:
return x - 2;
break;
case 6:
return x - 2;
break;
case 7:
return x - 1;
break;
}
}
int fangy(int x, int i) {
switch (i)
{
case 2:
return x + 1;
break;
case 3:
return x + 2;
break;
case 4:
return x + 2;
break;
case 5:
return x + 1;
break;
case 1:
return x - 1;
break;
case 7:
return x - 2;
break;
case 0:
return x - 2;
break;
case 6:
return x - 1;
break;
}
}
void dfs(int x, int y) {
add start, top;
start.x = x;
start.y = y;
temp.push(start);
again[x][y] = 1;
while (!temp.empty()) {
top = temp.front();
temp.pop();
for (int i = 0; i < 8; i++) {
int newx = fangx(top.x, i);
int newy = fangy(top.y, i);
if (newx<1 || newx>n || newy<1 || newy>m) {
continue;
}
if (again[newx][newy]==0) {
start.x = newx;
start.y = newy;
temp.push(start);
again[newx][newy] = 1;
ori[newx][newy] = ori[top.x][top.y] + 1;
}
}
}
}
int main() {
cin >> n >> m >> sx >> sy;
memset(ori, -1, sizeof(ori));
memset(again, 0, sizeof(again));
ori[sx][sy] = 0;
dfs(sx, sy);
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
cout << ori[i][j] << " ";
}
cout << endl;
}
}