北大 acm 3009

#include<iostream>
using namespace  std;
const int N=25;
char maze[N][N];
int w,h;
int count;

void dfs(int x,int y,int step)
{
	if (step>count)    //如果當前的步數超過了最小的步數,停止
	    return;

	int i;
	for(i=x+1;i<h;i++)  //往下走
	{
       if (i==x+1 && maze[i][y]=='1')
           break;

	   if (maze[i][y]=='3')       //保證獲取最小的步數
	   {
		   if(step<count)
			   count=step;
	   }

	   if (maze[i][y]=='1')
	   {
          maze[i][y]='0';
		  dfs(i-1,y,step+1);
		  maze[i][y]='1';
		  break;
	   }
	}

	for(i=x-1;i>=0;i--)  //往上走
	{
		if (i==x-1 && maze[i][y]=='1')
			break;

		if (maze[i][y]=='3')
		{
			if(step<count)
				count=step;
		}

		if (maze[i][y]=='1')
		{
			maze[i][y]='0';
			dfs(i+1,y,step+1);
			maze[i][y]='1';
			break;
		}
	}

	for(i=y-1;i>=0;i--)  //往左走
	{
		if (i==y-1 && maze[x][i]=='1')
			break;

		if (maze[x][i]=='3')
		{
			if(step<count)    
				count=step;
		}

		if (maze[x][i]=='1')
		{
			maze[x][i]='0';
			dfs(x,i+1,step+1);
			maze[x][i]='1';
			break;
		}
	}

	for(i=y+1;i<w;i++)  //往右走
	{
		if (i==y+1 && maze[x][i]=='1')
			break;

		if (maze[x][i]=='3')
		{
			if(step<count)
				count=step;
		}

		if (maze[x][i]=='1')
		{
			maze[x][i]='0';
			dfs(x,i-1,step+1);
			maze[x][i]='1';
			break;
		}
	}

}
int main()
{
	int i,j,x,y;
	while (cin>>w>>h)
	{
		count=11;
		if (w==0&&h==0)
	      break;
        for (i=0;i<h;i++)
        {
			for (j=0;j<w;j++)
			{
				cin>>maze[i][j];
				if (maze[i][j]=='2')
				{
					x=i;  y=j;
				}
			}
        }
		dfs(x,y,1);
		if (count>10)
			cout<<"-1"<<endl;
		else 
			cout<<count<<endl;
	}
	return 0;
}


上面的代碼分別編寫了上下左右四個方向,可以合併起來考慮,用一個二維數組表示四個方向,代碼長度可以縮短許多。

#include<iostream>
#include <cstring>
using namespace std;

const int N=25;

char maze[N][N];
int  dir[4][2]={{1,0},{0,-1},{-1,0},{0,1}};
int w,h;
int count;

void dfs(int x,int y,int step)
{
	if (step>count)
	   return;

	for (int i=0;i<4;i++)
	{
		int tmpx=x+dir[i][0];
		int tmpy=y + dir[i][1];

		if(maze[tmpx][tmpy]=='1')
			continue;

		while (1)
		{
			if (tmpx<0||tmpx==h ||tmpy<0 || tmpy==w)
			   break;

			else
			{
				if (maze[tmpx][tmpy]=='3')
				{
					if (step<count)
						count=step;
					return;
				}
				if (maze[tmpx][tmpy]=='1')
				{
					maze[tmpx][tmpy]='0';
					dfs(tmpx-dir[i][0],tmpy-dir[i][1],step+1);
					maze[tmpx][tmpy]='1';
					break;
				}
			}
			tmpx+=dir[i][0];
			tmpy+=dir[i][1];
			
		}
	}
}
int main()
{
	int i,j,x,y;
	while (cin>>w>>h)
	{
		count=11;
		if (w==0&&h==0)
	      break;
        for (i=0;i<h;i++)
        {
			for (j=0;j<w;j++)
			{
				cin>>maze[i][j];
				if (maze[i][j]=='2')
				{
					x=i;  y=j;
				}
			}
        }
		dfs(x,y,1);
		if (count>10)
			cout<<"-1"<<endl;
		else 
			cout<<count<<endl;
	}
	return 0;
}


 

發佈了36 篇原創文章 · 獲贊 12 · 訪問量 10萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章