• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

  • 联系
  • 订阅
  • 管理

View Post

sicily 1158. Pick numbers bfs

//这题一开始感觉是dp,状态转移方程为dp[i][j] = min(dp[i][j-1], dp[i-1][j]) + maze[i][j]
//提交上去WA
//后来发现这题不能用dp,因为题目要求的是正的最小值,状态转移方程的min会取到负数,
//当求出dp[n][m]为负数时,有可能存在一条和为正的路径
//注意到n,m都比较小,可以直接用bfs搜索过
#include <iostream>
#include <queue>
using namespace std;

const int N = 15;
const int INF = 1000000000;

int maze[N][N];
int n, m;
int ans;
int dx[] = {1, 0};
int dy[] = {0, 1};

struct status
{
	int row,col,sum;
	status() {}
	status (int row, int col, int sum)
	{
		this->row = row;
		this->col = col;
		this->sum = sum;
	}
};

void bfs()
{
	queue<status> Q;
	Q.push(status(1, 1, maze[1][1]));
	status p,tmp;

	while (!Q.empty())
	{
		p = Q.front();
		Q.pop();
		if (p.row == n && p.col == m && p.sum > 0)
			ans = min(p.sum, ans);
		
		for (int i = 0; i < 2; i++)
		{
			tmp = p;
			tmp.row += dx[i];
			tmp.col += dy[i];
			if (tmp.row >= 1 && tmp.row <= n && tmp.col >= 1 && tmp.col <= m)
			{
				tmp.sum += maze[tmp.row][tmp.col];
				Q.push(tmp);
			}
		}
	}
}

int main()
{
	while (cin >> n >> m)
	{
		for (int i = 1; i <= n; i++)
			for (int j = 1; j <= m; j++)
				cin >> maze[i][j];

		ans = INF;
		bfs();
		if (ans < INF)
			cout << ans << endl;
		else
			cout << -1 << endl;	
	}
	return 0;
}

posted on 2011-04-15 18:29  sysuwhj  阅读(488)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3