题目描述
有一个n*m的格子图,每个格子最多与其周围的四个相邻,不相邻的格子之间互相不可达。设一个4*6的格子图坐标如下:
123456
1######
2######
3######
4######
则(2,3)的格子与(1,3),(3,3),(2,2),(2,4)相邻。
格子与格子之间存在特殊的墙,阻止两个相邻的格子的移动。若(2,3)存在一堵左侧的墙,则(2,3)将无法直接到达(2,2),但(2,2)仍能到达(2,3)。
现给出每个格子周围墙的情况,求从给定的点(S,T)出发,到达每一个格子最少经过多少个格子。
输入 第一行为一个正整数T(T<=20),表示测试数据的组数。 对于每一组数据,第一行为n,m,S,T,(1<=n<=100, 1<=m<=100) (1<=S<=100) (1<=T<=100)。 后面有n行,每行m个数字,第i行第j列的数字x表示格子(i,j)周围墙的情况。x的二进制表示中,从低位到高位数第1,2,3,4位分别表示该格子在上、下、左、右方向是否有墙。若有则该位为1,否则为0。 |
样例输入 2 3 3 1 1 8 0 0 2 0 0 1 4 0 2 2 1 1 0 0 0 0 |
输出 对于每组数据,先输出一行"Case %:",其中%代表第i组数据。每组数据输出n行,每行包含m个整数,第i行第j个整数代表从(S,T)出发到(i,j)的最小路程。若不能到达,该位置为-1。 |
样例输出 Case 1: |
时间限制C/C++语言:1000MS其它语言:3000MS |
内存限制C/C++语言:65536KB其它语言:589824KB |
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
int main(){
int t;
cin >> t;
for (int i = 1; i <= t; i++){
int n, m, s, t;
cin >> n >> m >> s >> t;
vector<int>temp(m, -1);
vector<vector<int> >wall(n, temp);
vector<vector<int>> res(n, temp);
int num;
for (int i = 0; i<n; i++){
for (int j = 0; j<m; j++){
cin >> num;
wall[i][j] = num;
}
}
queue<pair<int, int>>q;
s--;
t--;
q.push(pair<int, int>(s, t));
res[s][t] = 0;
while (!q.empty()){
int size = q.size();
for (int i = 0; i < size; i++){
pair<int, int> p = q.front();
int x = p.first;
int y = p.second;
q.pop();
int dd = wall[x][y];
int step = res[x][y];
vector<int>direct;
for (int k = 0; k < 4; k++){
direct.push_back(dd % 2);
dd /= 2;
}
if (direct[0] == 0){//shang
if (x > 0 && res[x - 1][y] == -1){
res[x - 1][y] = step + 1;
q.push(pair<int, int>(x - 1, y));
}
}
if (direct[1] == 0){//xia
if (x+1 < n && res[x + 1][y] == -1){
res[x + 1][y] = step + 1;
q.push(pair<int, int>(x + 1, y));
}
}
if (direct[2] == 0){//zuo
if (y>0 && res[x][y-1] == -1){
res[x ][y-1] = step + 1;
q.push(pair<int, int>(x, y-1));
}
}
if (direct[3] == 0){//you
if (y+1<m && res[x][y + 1] == -1){
res[x][y + 1] = step + 1;
q.push(pair<int, int>(x, y + 1));
}
}
}
}
cout << "Case " << i << ":" << endl;
for (int i = 0; i < n; i++){
for (int j = 0; j < m; j++){
cout << res[i][j] << " ";
}
cout << endl;
}
}
//system("pause");
}