POJ 2488 DFS

39 篇文章 0 订阅

题目在http://poj.org/problem?id=2488

这个题目尝试用 collabedit写,虽然做了检查,不过依然不能做到bugfree。

题目比较简单


#include <stdio.h>
#include <memory.h>
#define MAX_GRID 26
#define MOVE_WAY 8
int g_Board[MAX_GRID][MAX_GRID];
int g_nRow, g_nCol;

struct Move
{
	int nColMove;
	int nRowMove;
};
Move g_Moves[MOVE_WAY] = {{-2,-1},{-2, 1}, {-1, -2}, {-1, 2}, 
                          {1, -2},{1, 2},  {2, -1},  {2, 1}}; //可以移动的方式,并且这些方式按照 获得字母序 的方式排好。

Move g_Path[MAX_GRID]; //record all the path during the recursion
bool IsLegal(int iRow, int iCol)
{
	if(iRow < 0 || iCol < 0 || iRow >= g_nRow || iCol >= g_nCol || g_Board[iRow][iCol] == 1)
	{ 
		return false;
	}
	return true;
}
//use dfs to search the board
bool WalkInBoard(int iRow, int iCol, int nSteps)
{
	g_Board[iRow][iCol] = 1;
	int newRow, newCol;
	nSteps++;
	if(nSteps == g_nRow * g_nCol)
	{
		//save the path
		return true;
	}
	for( int i = 0; i < MOVE_WAY ; i++)
	{
		newRow = g_Moves[i].nRowMove + iRow;
		newCol = g_Moves[i].nColMove + iCol;
		if(IsLegal(newRow, newCol))
		{
			if(WalkInBoard(newRow, newCol, nSteps))
			{
				g_Path[nSteps].nRowMove = newRow;//here is bug1, you write as g_Path[nSteps] = newRow
				g_Path[nSteps].nColMove = newCol;
				return true;
			}
		}
	}
	nSteps--;
	g_Board[iRow][iCol] = 0;
	return false;
}

int main()
{
	int ncase;
	int i,j;
	int icase;

	scanf("%d", &ncase);
	for( icase = 1; icase <= ncase; i++)
	{
		scanf("%d%d", &g_nRow, &g_nCol);
		memset(g_Board, 0, sizeof(g_Board));
		printf("Scenario #%d:\n",icase);
		for(i = 0; i < g_nCol; i++)
		{
			for( j = 0; j < g_nRow; j++)
			{
				if(WalkInBoard(j, i, 0))
				{
					g_Path[0].nRowMove  = j;
					g_Path[0].nColMove = i;
					int allStep = g_nRow * g_nCol;
					for( int k = 0; k < allStep; k++)
					{
						printf("%c%d",g_Path[k].nColMove + 'A',g_Path[k].nRowMove + 1);//here is bug 2, you write as i; ahah
					}
					printf("\n\n");//bug there, you write just \n, PE
					break;
				}
			}
			if( j != g_nRow)
				break;
		}
		if( i == g_nCol )
		{
			printf("impossible\n\n");
		}
		icase++;
	} 
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值