#include "iostream"
#include "queue"
using namespace std;
struct Node
{
int x, y;
int step;
};
bool test(int x, int y, int m, int n,int a[][10],int visit[][10]);
void BFS(int x,int y,int a[][10],int visit[][10],int m,int n);
int main()
{
int m, n;
cout<<"请输入矩阵的行数m和列数n"<<endl;
cin >> m >> n;
char temp;
int a[10][10];
int visit[10][10] = { 0 };
cout<<"请输入m行n列的矩阵"<<endl;
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
cin >> temp;
if (temp == '.')
a[i][j] = 0;//表示平地可以走
else if (temp == '*')
a[i][j] = -1;//表示障碍物,不可以走
else if (temp == 'S')//表示起点
a[i][j] = 10;
else if (temp== 'T')//表示终点
a[i][j] = 100;
}
}
for(int i=0;i<m;i++)
for (int j = 0; j < n; j++)
{
if (a[i][j] == 10)
{
BFS(i, j, a, visit, m, n);
}
}
system("pause");
return 0;
}
void BFS(int x, int y, int a[][10], int visit[][10],int m,int n)
{
int X[4] = { 0,0,1,-1 };
int Y[4] = { 1,-1,0,0 };
queue<Node *> nodeQueue;
Node *node=new Node();
node->x = x;
node->y = y;
node->step = 0;
nodeQueue.push(node);//将开始节点加入队列
visit[x][y] = 1;
while (!nodeQueue.empty())
{
Node *tnode;//指向队首节点
tnode = nodeQueue.front();
nodeQueue.pop();
if (a[tnode->x][tnode->y]==100)//表明到达终点
{
cout << tnode->step<<endl;
break;
}
for (int i = 0; i < 4; i++)
{
Node *tempnode = new Node();
tempnode->x = tnode->x + X[i];
tempnode->y = tnode->y + Y[i];
tempnode->step = tnode->step + 1;
if (test(tempnode->x, tempnode->y, m, n,a,visit))
{
visit[tempnode->x][tempnode->y] = 1;
nodeQueue.push(tempnode);
}
}
}
}
bool test(int x, int y,int m,int n,int a[][10],int visit[][10])//判断坐标是否合法
{
if (x >= 0 && x < m&&y>=0 && y < n&&a[x][y]!=-1&&visit[x][y]==0)
return true;//坐标合法
else
return false;//坐标越界
}