Chell是Valve Corporation开发的Portal视频游戏系列中的主角。
一天,她掉进了一个迷宫。迷宫可以看作是一个大小为n x m二维字符数组。它有4种房间。'S’代表Chell从哪开始(只有一个起点)。‘E’代表迷宫的出口(当chell抵达时,她将离开迷宫,该题目可能会有多个出口)。’*‘代表这个房间Chell可以经过。’#'代表一堵墙,Chell不能经过墙。
她可以每次上下左右移动到达一个房间,花费一分钟时间,但是不能到达墙。
现在,你能告诉我她最少需要多少时间离开这个迷宫吗?
如果她不能离开,返回-1
样例
样例1
输入:
[
['S','E','*'],
['*','*','*'],
['*','*','*']
]
输出: 1
解释:
Chell 从(0,0) 走到(0,1),花费1分钟。
样例2
输入:
[
['S','#','#'],
['#','*','#'],
['#','*','*'],
['#','*','E']
]
输出: -1
解释:
Chell 不能离开迷宫。
注意事项
我们保证迷宫的大小为 n x m,满足1<=n<=200,1<=m<=200 .
这里有且只有一个'S',保证有一个以上的'E'。
第一次:百分之80的地方time limeted
class Solution {
public:
/**
* @param Maze:
* @return: nothing
*/
struct point{
int x;
int y;
int step;
point(int x,int y)
{
this->x=x;
this->y=y;
this->step=0;
}
};
int Portal(vector<vector<char>> &Maze) {
if(Maze.size()==0) return -1;
if(Maze[0].size()==0) return -1;
int sr=0;
int sc=0;
int lenr=Maze.size();
int lenc=Maze[0].size();
search(Maze,sr,sc);//找到起点位置
queue<point> q;
vector<vector<bool>> visit(lenr,vector<bool>(lenc,false));
q.push(point(sr,sc));
while(!q.empty())
{
point front=q.front();
q.pop();
int x=front.x;
int y=front.y;
visit[x][y]=true;
if(Maze[x][y]=='#')
continue;
else if(Maze[x][y]=='E') return front.step;
if(x+1<lenc&&visit[x+1][y]==false)
{
point tmp(x+1,y);
tmp.step=front.step+1;
q.push(tmp);
}
if(y+1<lenr&&visit[x][y+1]==false)
{
point tmp(x,y+1);
tmp.step=front.step+1;
q.push(tmp);
}
if(y-1>=0&&visit[x][y-1]==false)
{
point tmp(x,y-1);
tmp.step=front.step+1;
q.push(tmp);
}
if(x-1>=0&&visit[x-1][y]==false)
{
point tmp(x-1,y);
tmp.step=front.step+1;
q.push(tmp);
}
}
return -1;
}
void search(vector<vector<char>> &Maze,int &row,int &col)//找到起点位置
{
int len=Maze[0].size();
for (int i = 0; i < Maze.size(); i++) {
for(int j = 0; j<Maze[0].size();j++)
{
if(Maze[i][j]=='S')
{
row=i;
col=j;
return;
}
}
}
}
};
一直卡着过不去,参考了九章算法
class Solution {
public:
/**
* @param Maze:
* @return: nothing
*/
struct node {
int x, y, step;
};
int Portal(vector<vector<char>> &Maze) {
int dx[5]={-1,1,0,0};
int dy[5]={0,0,-1,1};
int n = Maze.size();
int m = Maze[0].size();
int sx, sy, ex, ey;
int step[201][201];
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
step[i][j] = INT_MAX;
step[i][j] = INT_MAX;
if(Maze[i][j] == 'S') {
sx = i;
sy = j;
step[sx][sy] = 0;
}
}
}
node Start;
Start.x = sx;Start.y = sy;Start.step = 0;
queue<node>nodequeue;
nodequeue.push(Start);
while(!nodequeue.empty()) {
node head = nodequeue.front();
nodequeue.pop();
node New = head;
for (int i = 0; i < 4; i++) {
New.x = head.x + dx[i];
New.y = head.y + dy[i];
New.step = head.step + 1;
if(New.x < 0 || New.x >= n || New.y < 0 || New.y >= m || Maze[New.x][New.y] == '#') {
continue;
}
if (step[New.x][New.y] <= New.step) {
continue;
}
step[New.x][New.y] = New.step;
if (Maze[New.x][New.y] == 'E')
return New.step;
nodequeue.push(New);
}
}
return -1;
}
};