ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

DFS做法-问题 B: DFS or BFS?

2020-05-05 11:41:33  阅读:243  来源: 互联网

标签:stones node false startNode int DFS BFS ++ 做法


使用DFS的做法
AC代码

#include <stdio.h>
#include <vector>
using namespace std;

struct Node {
	int x, y;
	//存放石头的位置的集合
	vector<Node> stones;
} startNode, tempNode, stone;

char matrix[8][8];
int n;
bool isEnd = false;
bool isWin = false;

void input() {
	for(int i= 0; i < 8; i++) {
		for(int j = 0; j < 8; j++) {
			scanf("%c", &matrix[i][j]);
		}
		getchar();
	}
}
//把石头的位置存入startNode.stones
void findStones() {
	if(!startNode.stones.empty()) {
		startNode.stones.clear();
	}
	for(int i= 0; i < 8; i++) {
		for(int j = 0; j < 8; j++) {
			if(matrix[i][j] == 'S') {
				stone.x = i;
				stone.y = j;
				startNode.stones.push_back(stone);
			}
		}
	}
}


int X[] = {0, 0, 0, 1, -1, 1, 1, -1, -1};
int Y[] = {0, 1, -1, 0, 0, 1, -1, 1, -1};

bool check(Node &node) {
	if(node.x < 0 || node.x >= 8 || node.y < 0 || node.y >= 8) return false;
	for(vector<Node>::iterator it = node.stones.begin(); it != node.stones.end(); it++) {
		if(node.x == (*it).x && node.y == (*it).y)  return false;
		(*it).x++;
		//掉出矩阵,删除
		if((*it).x >= 8) {
			node.stones.erase(it);
		}
		//石头压住,结束
		if((*it).x == node.x && (*it).y == node.y) return false;
		//有个陷阱,就是遍历集合的时候还删除元素的话,会出错!增加个判断就能解决
		if(it == node.stones.end()) break;
	}
	return true;
}

void DFS(Node node) {
	if(node.stones.size() == 0) {
		isEnd = true;
		isWin = true;
		return;
	}
	for(int i = 0; i < 9; i++) {
		int newX = node.x + X[i];
		int newY = node.y + Y[i];
		tempNode.x = newX;
		tempNode.y = newY;
		tempNode.stones = node.stones;
		if(check(tempNode) && isEnd == false) {
			DFS(tempNode);
		}
	}
}

int main() {

	startNode.x = 7;
	startNode.y = 0;
	scanf("%d", &n);
	for(int i = 1; i <= n; i++) {
		isEnd = false;
		isWin = false;
		getchar();
		input();
		findStones();
		DFS(startNode);
		if(isWin) {
			printf("Case #%d: Yes\n", i);
		} else {
			printf("Case #%d: No\n", i);
		}

	}
	return 0;
}


标签:stones,node,false,startNode,int,DFS,BFS,++,做法
来源: https://blog.csdn.net/qq_44854593/article/details/105916863

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有