zoukankan      html  css  js  c++  java
  • 洛谷P2324 [SCOI2005]骑士精神

    题目链接:

    kmakma!

    题目分析:

    启发式搜索入门经典题

    • 迭代加深:
      本题最大次数15次,超过15次直接return
    • 估价函数:
      当前走的次数和与答案的偏差值,超过16直接return

    代码:

    #include <bits/stdc++.h>
    using namespace std;
    inline int read() {
    	int cnt = 0, f = 1; char c = getchar();
    	while (!isdigit(c)) {if (c == '-') f = -f; c = getchar();}
    	while (isdigit(c)) {cnt = (cnt << 3) + (cnt << 1) + c - '0'; c = getchar();}
    	return cnt * f;
    }
    const char check[10][10] = 
    {{'1', '1', '1', '1', '1'},
     {'0', '1', '1', '1', '1'},
     {'0', '0', '*', '1', '1'},
     {'0', '0', '0', '0', '1'},
     {'0', '0', '0', '0', '0'}};
    const int dx[10] = {1, -1, 1, -1, 2, -2, 2, -2};
    const int dy[10] = {2, -2, -2, 2, 1, -1, -1, 1};
    char mapp[10][10];
    int T, ans;
    int spacex, spacey;
    int test() {
    	int tot = 0;
    	for (register int i = 0; i < 5; i++)
    		for (register int j = 0; j < 5; j++)
    			if (mapp[i][j] != check[i][j]) ++tot;
    //	cout<<tot<<endl;
    	return tot;
    }
    void dfs_(int cnt, int x, int y, int lastx, int lasty) {
    //	cout<<x<<" "<<y<<endl;
    	if (cnt + test() > 16) return;
    	if (cnt >= ans) return;
    	if (!test()) {ans = min(ans, cnt); return;}
    	for (register int i = 0; i <= 7; ++i) {
    			if (x + dx[i] < 0 || x + dx[i] > 4) continue;
    			if (y + dy[i] < 0 || y + dy[i] > 4) continue;
    			if (x + dx[i] == lastx && y + dy[i] == lasty) continue;
    				swap(mapp[x + dx[i]][y + dy[i]], mapp[x][y]);
    				dfs_(cnt + 1, x + dx[i], y + dy[i], x, y);
    				swap(mapp[x + dx[i]][y + dy[i]], mapp[x][y]);
    	}
    }
    int main() {
    	T = read();
    	while (T--) {
    		ans = 10000;
    		memset(mapp, 0, sizeof(mapp));
    		for (register int i = 0; i < 5; ++i) scanf("%s", mapp[i]);
    		for (register int i = 0; i < 5; ++i)
    			for (register int j = 0; j < 5; ++j)
    				if (mapp[i][j] == '*') spacex = i, spacey = j;
    		dfs_(0, spacex, spacey, -1, -1);
    		ans == 10000 ? printf("-1
    ") : printf("%d
    ", ans);
    	}
    	return 0;
    }
    
  • 相关阅读:
    CSS3相关编码规范
    WEB开发中常见的漏洞
    Python常用端口扫描
    33、Django实战第33天:我的消息
    32、Django实战第32天:我的收藏
    31、Django实战第31天:我的课程
    30、Django实战第30天:修改邮箱和用户信息
    29、Django实战第29天:修改密码和头像
    28、Django实战第28天:个人信息展示
    27、Django实战第27天:全局搜索功能开发
  • 原文地址:https://www.cnblogs.com/kma093/p/11319312.html
Copyright © 2011-2022 走看看