深搜实现全排列
#include <iostream>
using namespace std;
int n;
int a[10],book[10];
void dfs(int cur)
{
if(cur == n + 1)
{
for(int i = 1;i<=n;i++)
cout<<a[i];
cout<<endl;
return;
}
else
{
for(int i = 1;i<=n;i++)
{
if(book[i] == 0)
{
a[cur] = i;
book[i] = 1;
dfs(cur+1);
book[i] = 0;
}
}
}
}
int main()
{
while(cin >> n)
{
if(n == 0)
break;
dfs(1);
}
return 0;
}
最短距离问题
5 5
#.s#e
..##.
...#.
.##..
.....
求s到e的最短距离
#include <iostream>
using namespace std;
char a[100][100];
int book[100][100];
int n,m,stx,sty,enx,eny;
int Min = 9999999;
int dx[] = {1,-1,0,0};
int dy[] = {0,0,1,-1};
void dfs(int x,int y,int step)
{
if(x == enx && y == eny)
{
if(step < Min)
Min = step;
return;
}
else
{
for(int i = 0;i<4;i++)
{
int xx = x + dx[i];
int yy = y + dy[i];
if(xx < 0 || yy < 0 || xx >=n || yy >=m || a[xx][yy] == '#' || book[xx][yy] == 1)
continue;
book[xx][yy] = 1;
dfs(xx,yy,step+1);
book[xx][yy] = 0;
}
}
}
int main()
{
cin >> n >> m;
for(int i = 0;i<n;i++)
{
for(int j = 0;j<m;j++)
{
cin >> a[i][j];
if(a[i][j] == 's')
{
stx = i;
sty = j;
}
if(a[i][j] == 'e')
{
enx = i;
eny = j;
}
}
}
dfs(stx,sty,0);
cout<<Min<<endl;
return 0;
}
仓促之下写的代码-,-,改天再补 逃:)