acwing算法基础课(第三讲 搜索与图论)

38 阅读1分钟

输出样例:

1 2 3

1 3 2

2 1 3

2 3 1

3 1 2

3 2 1

#include <bits/stdc++.h>

using namespace std;

const int N = 10;

int n;

int path[N];

bool st[N];

void dfs(int u){

if(n == u) {

for(int i = 0;i < n;i++) printf("%d ",path[i]);

puts("");

return;

}

for(int i = 1;i <= n;i++){

if(!st[i]){

path[u] = i;

st[i] = true;

dfs(u+1);

回溯

st[i] = false;

}

}

}

int main(){

scanf("%d",&n);

dfs(0);

return 0;

}

分析: 排序最重要的是顺序,以何种顺序能将所有的方案走一遍是关键

每一个DFS算法都对应着一个DFS树,我们可以在此基础上考虑回溯和剪枝

DFS又称暴搜,

数据结构     空间

DFS   stack       O(n)       不具有最短路性

843. n-皇后问题
思路一:

按着全排列的思路,枚举每一行可以放皇后的位置

#include <bits/stdc++.h>

using namespace std;

const int N1 = 10,N2 = 20;

int n;

char g[N1][N1];

bool col[N1],dg[N2],udg[N2];

void dfs(int u){

if(n == u){

for(int i = 0;i < n;i++) puts(g[i]);

puts("");

return;

}

for(int i = 0;i < n;i++){

if(!col[i] && !dg[u+i] && !udg[n - u + i]){

g[u][i] = 'Q';

col[i] = dg[u+i] = udg[n - u + i] = true;

dfs(u+1);

col[i] = dg[u+i] = udg[n - u + i] = false;

g[u][i] = '.';

}

}

}

int main(){

scanf("%d",&n);

for(int i = 0;i < n;i++){

for(int j = 0;j < n;j++){

g[i][j] = '.';

}

}

dfs(0);

return 0;

}

思路二:

枚举每一格

#include <bits/stdc++.h>

using namespace std;

const int N1 = 10,N2 = 20;

int n;

char g[N1][N2];

bool row[N1],col[N1],dg[N2],udg[N2];

void dfs(int x,int y,int s){

if(y == n) y = 0,x++;

if(x == n){

if(s == n){

for(int i = 0;i < n;i++) puts(g[i]);

puts("");

}

return;

}

// 不放皇后

dfs(x,y+1,s);

// 放皇后

if(!row[x] && !col[y] && !dg[x + y] && !udg[n + x - y]){

g[x][y] = 'Q';

row[x] = col[y] = dg[x+y] = udg[x-y+n] = true;

dfs(x,y+1,s+1);

g[x][y] = '.';

row[x] = col[y] = dg[x+y] = udg[x-y+n] = false;

}

}

int main(){

scanf("%d",&n);

for(int i = 0;i < n;i++){

for(int j = 0;j < n;j++){

g[i][j] = '.';

}

}

dfs(0,0,0);

return 0;

}

BFS

BFS有一个很明显的模板

while(!queue.empty()){

auto t = queue.front();

queue.pop();

queue.push(…);

}

844. 走迷宫

给定一个n*m的二维整数数组,用来表示一个迷宫,数组中只包含0或1,其中0表示可以走的路,1表示不可通过的墙壁。

最初,有一个人位于左上角(1, 1)处,已知该人每次可以向上、下、左、右任意一个方向移动一个位置。

请问,该人从左上角移动至右下角(n, m)处,至少需要移动多少次。

数据保证(1, 1)处和(n, m)处的数字为0,且一定至少存在一条通路。

输入格式

第一行包含两个整数n和m。

接下来n行,每行包含m个整数(0或1),表示完整的二维数组迷宫。

输出格式

输出一个整数,表示从左上角移动至右下角的最少移动次数。

数据范围

1≤n,m≤100

输入样例:

5 5

0 1 0 0 0

0 1 0 1 0

0 0 0 0 0

0 1 1 1 0

0 0 0 1 0

输出样例:

8

#include <bits/stdc++.h>

using namespace std;

const int N = 100 + 10;

typedef pair<int,int> PII;

int g[N][N];

int d[N][N];

int n,m;

queue q;

int bfs(){

memset(d,-1,sizeof(d));

q.push({0,0});

d[0][0] = 0;

int dx[4] = {-1,0,1,0},dy[4] = {0,1,0,-1};

while(!q.empty()){

auto t = q.front();

q.pop();

for(int i = 0;i < 4;i++){

int x = t.first +dx[i],y = t.second +dy[i];

if(x >= 0 && x < n && y >= 0 && y < m && d[x][y] == -1 && g[x][y] == 0){

d[x][y] = d[t.first][t.second] + 1;

q.push({x,y});

}

}

}

return d[n-1][m-1];

}