graph.h
#ifndef GRAPH_H
#include <stdio.h>
#include <stdlib.h>
#define MaxSize 500
#define MaxPoint 10000
enum graph_val { hasmoved = -1, can = 0, block = 1, shop = 2, user = 3 };
int vis[MaxSize][MaxSize];//记录已走过
typedef struct {
int node[MaxSize][MaxSize];//路图
int milk_count;//奶茶店个数
int user_count;//客户个数
int block_count;//不可走个数
int edge_count;//边长度(不含边框)
}Graph;
#endif // !GRAPH_H
queue.h
#ifndef QUEUE_H
#include "graph.h"
typedef struct
{
int x, y, w;
}Point;
typedef struct
{
Point data[MaxPoint];
int front, rear;
int count;//队列长度
}QuType;
void InitQueue(QuType*& q)
{
q = (QuType*)malloc(sizeof(QuType));
q->front = q->rear = 0;
q->count = 0;
}
void DestroyQueue(QuType*& q)
{
free(q);
}
bool QueueEmpty(QuType* q)
{
if (q->count == 0) {
return false;
}
else
return true;
}
bool enQueue(QuType*& q, Point e)
{
if (q->rear == MaxPoint - 1)
{
return false;
}
q->data[q->rear] = e;
q->rear++;
q->count++;
return true;
}
Point deQueue(QuType*& q)
{
Point tmp;
tmp.x = -1;
tmp.y = -1;
tmp.w = -1;
if (q->front == q->rear)
{
return tmp;
}
tmp = q->data[q->front];
q->front++;
q->count--;
return tmp;
}
Point getTop(QuType* q) {
return q->data[q->front];
}
#endif // !QUEUE_H
main.cpp
#include "queue.h"
QuType* qu;
int n, m, k, d;
int dx[] = { 0, 0, 1, -1 };
int dy[] = { 1, -1, 0, 0 };
int bfs(Graph* g) {
int sum = 0;
while (QueueEmpty(qu)) {
Point p = getTop(qu);
deQueue(qu);
int i;
Point cur;
for (i = 0; i < 4; i++) {
int xx = p.x + dx[i];
int yy = p.y + dy[i];
if (xx >= 1 && xx <= g->edge_count && yy >= 1 && yy <= g->edge_count && !vis[xx][yy]) {
sum += g->node[xx][yy] * (p.w + 1);
vis[xx][yy] = 1;
cur.x = xx;
cur.y = yy;
cur.w = p.w + 1;
enQueue(qu, cur);
}
}
}
return sum;
}
int main() {
Graph* g = (Graph*)malloc(sizeof(Graph));
InitQueue(qu);
printf("请分别输入方格图大小、奶茶分店数量、客户数量、不能经过的点的数量:");
scanf("%d %d %d %d", &n, &m, &k, &d);
g->edge_count = n;
g->milk_count = m;
g->user_count = k;
g->block_count = d;
//初始化内容
for (int i = 1; i < n + 1; i++) {
for (int j = 1; j < n + 1; j++) {
g->node[i][j] = 0;
vis[i][j] = 0;
}
}
//初始化奶茶店
for (int i = 0; i < g->milk_count; i++) {
int x, y;
printf("请输入第%d个奶茶店的x、y坐标:", i + 1);
scanf("%d %d", &x, &y);
Point shop;
shop.x = x;
shop.y = y;
shop.w = 0;
enQueue(qu, shop);
}
//初始化客户
for (int i = 0; i < g->user_count; i++) {
int x, y, count;
printf("请输入第%d个客户的x、y坐标和订单数:", i + 1);
scanf("%d %d %d", &x, &y, &count);
g->node[x][y] += count;
}
//初始化不可走
for (int i = 0; i < g->block_count; i++) {
int x, y;
printf("请输入第%d个不可走的x、y坐标:", i + 1);
scanf("%d %d", &x, &y);
vis[x][y] = 1;
}
printf("\n最低总成本为:%d\n", bfs(g));
DestroyQueue(qu);
return 0;
}