最近我用c ++练习算法.在这里练习:poj
我发现两个非常混乱的问题.我写了一个MAZE类,在MAZE中有三个主要功能,它们是
int left_path();int right_path();int mini_path();
打印答案的函数:
void display(){
cout<<left_path()<<" "<<right_path()<<" ";
cout<<mini_path()<<endl;
}
Run Code Online (Sandbox Code Playgroud)
程序可以正常工作.我们看到函数display()可以很容易; 我这样写
void display(){
cout<<left_path()<<" "<<right_path()<<" "<<mini_path()<<endl;
}
Run Code Online (Sandbox Code Playgroud)
只有一个变化;但是程序无法工作,它就像无限循环一样.
以下是另一个问题:函数mini_path的框架是这样的
int maze::mini_path(){
ini();
queue<pair<int,int> > q;
q.push(make_pair(x,y));
while(!q.empty()){
pair<int,int> tmp=q.front();
q.pop();
int t=...;
if(E){
return t;
}
if(E){
S
}
if(E){
S
}
if(E){
S
}
if(E){
S
}
}
return -1;
}
Run Code Online (Sandbox Code Playgroud)
如果最后有"return -1",则该函数正常工作,否则函数返回随机大数.
该程序只在一个文件中,我使用枪编译器.
我没有显示总代码,因为我认为没有人想看到它们.我只是想问一下哪些问题可能导致奇怪的行为.
源代码(问题2简化):
typedef enum {LEFT=-1,RIGHT=1,UP,DOWN} direction;
ifstream fin("file_test3.txt");
class maze{
public:
maze(){input();}
int mini_path();
void input();
void display(){
cout<<mini_path()<<endl;
}
private:
bool is_not_dest(){
return !(x==d_x && y==d_y);
}
void ini_dir()
{
if(e_x==0) dir=DOWN;
else if(e_x==height-1) dir=UP;
else if(e_y==0) dir=RIGHT;
else dir=LEFT;
}
void ini(){
x=e_x;
y=e_y;
path_lenth=1;
ini_dir();
}
direction dir,d;
int width,height,maze_map[40][40],path_lenth;
int x,y,e_x,e_y,d_x,d_y;
};
void maze::input()
{
fin>>width>>height;
char sym;
for(int i=0;i<height;++i)
for(int j=0;j<width;++j){
fin>>sym;
if(sym=='#')
maze_map[i][j]=1;
else if(sym=='.')
maze_map[i][j]=0;
else if(sym=='S'){
maze_map[i][j]=-1;
e_x=i;
e_y=j;
}
else {
maze_map[i][j]=-2;
d_x=i;
d_y=j;
}
}
}
int maze::mini_path()
{
ini();
queue<pair<int,int> > q;
if(dir==LEFT) {maze_map[x][--y]=2;}
else if(dir==RIGHT) {maze_map[x][++y]=2;}
else if(dir==UP) {maze_map[--x][y]=2;}
else {maze_map[++x][y]=2;}
q.push(make_pair(x,y));
while(!q.empty()){
pair<int,int> tmp=q.front();
q.pop();
x=tmp.first;
y=tmp.second;
int t=maze_map[x][y]+1;
if((x==d_x && (y-d_y==1 || y-d_y==-1)) ||(y==d_y && (x-d_x==1||x-d_x==-1))){
return t;
}
if(maze_map[x-1][y]==0){
maze_map[x-1][y]=t;
q.push(make_pair(x-1,y));
}
if(maze_map[x+1][y]==0){
maze_map[x+1][y]=t;
q.push(make_pair(x+1,y));
}
if(maze_map[x][y-1]==0){
maze_map[x][y-1]=t;
q.push(make_pair(x,y-1));
}
if(maze_map[x][y+1]==0){
maze_map[x][y+1]=t;
q.push(make_pair(x,y+1));
}
}
return -1;
}
main()
{
int n;
fin>>n;
while(n-- >0){
class maze m;
m.display();
}
}
Run Code Online (Sandbox Code Playgroud)
我看到了!你能看见它吗?:)
#include <iostream>
using namespace std;
int foo(int bar)
{
cout << bar << endl;
return bar;
}
int _tmain(int argc, _TCHAR* argv[])
{
cout << foo(1) << foo(2) << foo(3) << endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出:
3
2
1
123
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
123 次 |
| 最近记录: |