7-3 解答
- 一開始全部地方都是沒走過
- 若「超出邊界」或「走過了」或「是x」,就停止
- 注意使用陣列時不可以超出範圍
- 往上下左右亂走,走過要標記已走過
- 遇到 O 就記錄下來
#include<iostream>
using namespace std;
int max_x, max_y;
char maze[105][105];
bool visited[105][105];
bool isCookieFound;
void run( int y, int x )
{
}
int main()
{
int start_x, start_y;
while( cin >> max_x >> max_y )
{
run( start_y, start_x );
}
return 0;
}
解答
#include<iostream>
using namespace std;
int max_x, max_y;
char maze[105][105];
bool visited[105][105];
bool isCookieFound;
void run( int y, int x )
{
if( x < 0 || x >= max_x || y < 0 || y >= max_y || isCookieFound )
return;
if( visited[y][x] == true || maze[y][x] == 'x' )
return;
visited[y][x] = true;
if( maze[y][x] == 'O' )
isCookieFound = true;
run( y-1, x );
run( y+1, x );
run( y, x-1 );
run( y, x+1 );
}
int main()
{
int i, j, start_x, start_y;
while( cin >> max_x >> max_y )
{
for( i = 0 ; i < max_y ; i++ )
for( j = 0 ; j < max_x ; j++ )
{
cin >> maze[i][j];
visited[i][j] = false;
if( maze[i][j] == 'M' )
{
start_y = i;
start_x = j;
}
}
isCookieFound = false;
run( start_y, start_x );
if( isCookieFound )
cout << "Yes!" << endl;
else
cout << "Oh, no!" << endl;
}
return 0;
}