目前刷不动题目,继续看书为以后刷题目做铺垫。
这次研究了以前没敢用的广度优先搜索,用函数队列做循环基础。
就是谈谈队列的感受
队列就像找书中的以前夹着的一个小纸条,广度优先就是一层一层的翻,深度就是看心情随机看一面,没有就把这页给撕掉。
练习对象走迷宫:
输入 n*m矩形
0可以走,2不可以走
起点的地方字符为‘A’
终点为最后一行最后一个地址
不能到输出:Impossible
能到达则输出步数。
#include <iostream>
#include<queue>
#include<cstring>
#include<cstdio>
using namespace std;
typedef pair <int , int > p;
int main()
{
p q, z;
int arr1[4] = {1, 0, -1, 0}, arr2[4] = {0, 1, 0, -1};
int n, m, i, j, c[100][100], v[100][100];
char a[100][100];
p b[100];
queue <p> que;
cin >> n >> m;
memset ( c, 0, sizeof ( c ) );
memset ( v, 0, sizeof ( v ) );
z.first = n - 1;
z.second = m - 1;
for ( i = 0; i < n; i++ ) {
scanf ( "%s", &a[i] );
for ( j = 0; j < m; j++ ) {
if ( a[i][j] == 'A' ) {
q.first = i;
q.second = j;
}
}
}
que.push ( q );
while ( que.size() ) {
p temp = que.front();
que.pop();
if ( temp.first == z.first && temp.second == z.second ) break;
for ( i = 0; i < 4; i++ ) {
p temp2;
temp2.first = temp.first + arr1[i];
temp2.second = temp.second + arr2[i];
if ( temp2.first >= 0 && temp2.first < n && temp2.second >= 0 && temp2.second < m && v[temp2.first][temp2.second] == 0 && a[temp2.first][temp2.second] != '2' ) {
v[temp2.first][temp2.second] = 1;
c[temp2.first][temp2.second] = c[temp.first][temp.second] + 1;
que.push ( temp2 );
}
}
}
if ( c[n - 1][m - 1] == 1000000 ) cout << "Impossible" << endl;
else cout << c[n - 1][m - 1] << endl;
}