Tags » BF's

Please collect the notes of BFS from the xerox center tomorrow

Notes

BFS and DFS

Breadth-first search is an algorithm for traversing or searching tree or graph data structures. It starts at the tree root ( or some arbitrary node of a graph) and explores the neighbor nodes first, before moving to next level neighbors. 38 more words

Algorithm

1837.isenbaev's Numbers Solution-Timus

Pure BFS question,need to mark names(nodes) level wise 1,2,3..


#include <bits/stdc++.h>
using namespace std;
#define maxx 500 
int vis;
#define pb push_back
vector<int>G;
map<string,int>m;
vector<string>vc;
void bfs()
{
  if(m.find("Isenbaev")!=m.end())
  {
   vis]=0;
   queue<int>q;
   q.push(m["Isenbaev"]);
   while(!q.empty())
   {
   	int src=q.front();
   	q.pop();
   	for(int i=0;i<G.size();i++)
      {
   		if(vis[i]]==-1)
   		{     
   			  vis[i]]=vis+1;
   			  q.push(G[i]);
   		}
      }
   }
  }
}
int main() { 
	int n;
	cin>>n;
	int V=0;
	memset(vis,-1,sizeof vis);
	getchar();
	while(n--)
	{
		string u,v,w;
		cin>>u>>v>>w;
		if(m.find(u)==m.end())m[u]=V++;
		if(m.find(v)==m.end())m[v]=V++;
		if(m.find(w)==m.end())m[w]=V++;
		G].pb(m[v]);G].pb(m[u]);G].pb(m[w]);
		G].pb(m[u]);G].pb(m[w]);G].pb(m[v]);
	}
    bfs();
    for(auto it=m.begin();it!=m.end();++it)
    {
         if(vis==-1)
            cout<<it->first<<" undefined\n";
         else 
            cout<<it->first<<" "<<vis<<endl;
    }
	return 0;
} 32 more words
Timus

From BFS to LPA*

Breadth-first search (BFS) is an algorithm used in traversing or searching a graph data structure (whether it’s directed or not).

It starts at some node of a graph, and explores all the connected nodes to this node (its neighbors) before moving to the next level of the neighbors. 1,257 more words

Algorithms

UVa 429 - Word Transformation


/*
User ID: turing_13
Link: http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=24&page=show_problem&problem=370
*/

/*
         +-+ +-+ +-+
         |R| |.| |S|
         +-+ +-+ +-+
 */

#include <bits/stdc++.h>

#define pii             pair <int,int>
#define sc              scanf
#define pf              printf
#define Pi              2*acos(0.0)
#define ms(a,b)         memset(a, b, sizeof(a))
#define pb(a)           push_back(a)
#define MP              make_pair
#define db              double
#define ll              long long
#define EPS             10E-10
#define ff              first
#define ss              second
#define sqr(x)          (x)*(x)
#define D(x)            cout<<#x " = "<<(x)<<endl
#define VI              vector <int>
#define DBG             pf("Hi\n")
#define MOD             100007
#define MAX             10000
#define CIN             ios_base::sync_with_stdio(0); cin.tie(0)
#define SZ(a)           (int)a.size()
#define sf(a)           scanf("%d",&a)
#define sff(a,b)        scanf("%d%d",&a,&b)
#define sfff(a,b,c)     scanf("%d%d%d",&a,&b,&c)
#define loop(i,n)       for(int i=0;i<n;i++)
#define REP(i,a,b)      for(int i=a;i<b;i++)
#define TEST_CASE(t)    for(int z=1;z<=t;z++)
#define PRINT_CASE      printf("Case %d: ",z)
#define all(a)          a.begin(),a.end()
#define intlim          2147483648
#define inf             1000000
#define ull             unsigned long long

using namespace std;


//map <string,int> mp;
map <string,bool> visited;
map <string,int> d;
map< string,vector<string> >graph;
string str1;
vector <string> v;

bool test(string s1,string s2)
{
    int cnt=0;
    loop(i,SZ(s1))
    {
        if(s1[i]!=s2[i])
            cnt++;
        if(cnt==2) return false;
    }
    return true;
}

int BFS(string str1, string str2)
{
    visited=1;
    queue<string>Q;
    d=0;
    Q.push(str1);
    while(!Q.empty())
    {
        string p=Q.front();
        Q.pop();
        if(p==str2) return d;
        for(int i=0; i<SZ(graph[p]); i++)
        {
            string q=graph[p][i];
            if(visited[q]==0)
            {
                visited[q]=1;
                d[q]=d[p]+1;
                Q.push(q);
            }
        }
    }
}

int main()
{
    ///freopen("in.txt","r",stdin);
    ///freopen("out.txt","w",stdout);
    int t;
    char c;
    sf(t);
    while(t--)
    {
        while(cin>>str1 && str1!="*")
        {
            int x=SZ(str1);
            v[x].pb(str1);
            loop(i,SZ(v[x]))
            {
                string temp=v[x][i];
                if(test(str1,temp))
                {
                    graph.pb(temp);
                    graph.pb(str1);
                }
            }
        }
        getchar();
        string ss1,ss2,str2;
        while(1)
        {
            getline(cin,str2);
            if(str2=="") break;
            bool test=0;
            int xx=str2.size();
            loop(i,xx)
            {
                if(str2[i]==' ') {test=1;continue;}
                if(!test) ss1+=str2[i];
                else ss2+=str2[i];
            }
            int ans= BFS(ss1,ss2);
            cout<<ss1<<" "<<ss2<<" "<<ans<<endl;
            visited.clear();
            d.clear();
            ss1.clear();
            ss2.clear();
            str2.clear();
        }
        if(t)
            cout<<endl;
    }
    return 0;
}

UVa

BFS Algorithm in C

I prepared this BFS algorithm for solving UVa problems. This has to be used Adjacency List I prepared Before.


#include <stdbool.h>
#define TOTAL_NODE 100
#define INVALID 2147483647

int BFS(int startNode,int endNode,int startCost);
void ClearBFSResult();

int BFS(int startNode,int endNode,int startCost){

    Node *bfsTmpNode, *bfsTmpParentNode, *bfsGarbageNode,*bfsListTraversal;

    bfsTmpNode = GetNodeBaseAddress(startNode);
    if(bfsTmpNode==NULL){
        return 0;
    }
    InitializeQueue();
    bfsTmpNode->rVisited = true;
    bfsTmpNode->rCost = startCost;
    bfsTmpNode->rPreviousNode = NULL;
    Enqueue(bfsTmpNode,NULL);

    while(Dequeue(&bfsTmpParentNode,&bfsGarbageNode)){
        bfsListTraversal = bfsTmpParentNode;

        while(1){
            bfsListTraversal = bfsListTraversal->iNextNode;
            if(bfsListTraversal==NULL) break;

            bfsTmpNode = bfsListTraversal->bBaseAddress;
            if(bfsTmpNode->rVisited) continue;
            bfsTmpNode->rVisited = true;
            bfsTmpNode->rCost = bfsTmpParentNode->rCost + 1;

            bfsTmpNode->rPreviousNode = bfsTmpParentNode;
            if(bfsTmpNode->iNodeName == endNode){
                return bfsTmpNode->rCost;
            }
            Enqueue(bfsTmpNode,NULL);
        }
    }

    return 0;
}


void ClearBFSResult(){
    int i;
    for(i=0;i<NodeIndexHead;i++){
        AllNodeList[i]->rCost = INVALID;
        AllNodeList[i]->rPreviousNode = NULL;
        AllNodeList[i]->rVisited = false;
    }

}
C

UVa Problem Solution: 336 - A Node Too Far

Link: http://uva.onlinejudge.org/external/3/336.pdf
#include <stdio.h>
#include <stdlib.h>

#include <stdbool.h>
#define TOTAL_NODE 100
#define INVALID 2147483647


typedef struct mNode{
    int iNodeName;
    int iEdgeWeight;
    bool rVisited;
    int rCost;
    struct mNode *iNextNode;
    struct mNode *rPreviousNode;
    struct mNode *bBaseAddress;

}Node;

Node *AllNodeList;
void PutInNodeList(int FromNode, int ToNode, int EdgeWeight);
Node * GetNodeBaseAddress(int NodeName);
int GetNodeDegree(int NodeName);
int NodeIndexHead = 0;
void SetupNode(Node *mNodeAddress, int mNodeName, int mEdgeWeight, int mCost, Node *mNodeBaseAddress);
int TotalNodeInGraph(void);
int TotalEdgeInGraph(void);
void UpdateNodeValues(Node *mNodeAddress, int mEdgeWeight, Node *mNextNode, int mCost, Node *mPreviousNode, int mVisited);
void ClearBFSResult();
void ClearGRAPH();

void Enqueue(Node *,Node *);
bool Dequeue(Node **,Node **);

void BFS(int startNode,int startCost);

int main()
{

    freopen("input.txt","r",stdin);
    int caseCount,i,f,s,tmp,caseNumber=0;
    scanf("%d",&caseCount);
    while(caseCount!=0){
        for(i=0;i<caseCount;i++){
            scanf("%d%d",&f,&s);
            PutInNodeList(f,s,0);
            PutInNodeList(s,f,0);
        }
        scanf("%d%d",&f,&s);
        while(s|f){
            caseNumber++;
            tmp=0;
            BFS(f,s);
            for(i=0;i<NodeIndexHead;i++){
                if(!(AllNodeList[i]->rVisited)) tmp++;
            }
            printf("Case %d: %d nodes not reachable from node %d with TTL = %d.\n",caseNumber,tmp,f,s);
            scanf("%d%d",&f,&s);
            ClearBFSResult();
        }
        scanf("%d",&caseCount);
        ClearGRAPH();
    }


    return 0;
}


void PutInNodeList(int FromNode, int ToNode, int EdgeWeight){
    Node *tempNode = GetNodeBaseAddress(FromNode);

    if(tempNode != NULL){
        while(tempNode->iNextNode != NULL){
            tempNode = tempNode->iNextNode;
        }
        Node *tmp = (Node*) malloc(1 * sizeof(Node));

        Node *baseAddress = GetNodeBaseAddress(ToNode);
        if(baseAddress == NULL){
            baseAddress = (Node*) malloc(1 * sizeof(Node));
            SetupNode(baseAddress,ToNode,INVALID,INVALID,baseAddress);
            AllNodeList = baseAddress;
        }

        SetupNode(tmp,ToNode,EdgeWeight,INVALID,baseAddress);
        tempNode->iNextNode = tmp;

    }else{
        Node *tmp1 = (Node*) malloc(1 * sizeof(Node));
        SetupNode(tmp1,FromNode,INVALID,INVALID,tmp1);
        AllNodeList = tmp1;
        int tmpNodeHead = NodeIndexHead-1;

        Node *baseAddress = GetNodeBaseAddress(ToNode);
        if(baseAddress == NULL){
            baseAddress = (Node*) malloc(1 * sizeof(Node));
            SetupNode(baseAddress,ToNode,INVALID,INVALID,baseAddress);
            AllNodeList = baseAddress;
        }

        Node *tmp2 = (Node*) malloc(1 * sizeof(Node));
        SetupNode(tmp2,ToNode,EdgeWeight,INVALID,baseAddress);
        AllNodeList -> iNextNode = tmp2;
    }
}

void SetupNode(Node *mNodeAddress, int mNodeName, int mEdgeWeight, int mCost, Node *mNodeBaseAddress){
    mNodeAddress->iEdgeWeight = mEdgeWeight;
    mNodeAddress->iNextNode = NULL;
    mNodeAddress->iNodeName = mNodeName;
    mNodeAddress->rCost = mCost;
    mNodeAddress->rPreviousNode = NULL;
    mNodeAddress->rVisited = false;
    mNodeAddress->bBaseAddress = mNodeBaseAddress;
}

void UpdateNodeValues(Node *mNodeAddress,
                      int mEdgeWeight,
                      Node *mNextNode,
                      int mCost,
                      Node *mPreviousNode,
                      int mVisited){
    if(mEdgeWeight!=INVALID){
        mNodeAddress->iEdgeWeight=mEdgeWeight;
    }

    if(mNextNode != NULL){
        mNodeAddress->iNextNode = mNextNode;
    }

    if(mCost != INVALID){
        mNodeAddress->rCost = mCost;
    }

    if(mPreviousNode!=NULL){
        mNodeAddress->rPreviousNode=mPreviousNode;
    }
    if(mVisited != 0){
        if(mVisited>0){
            mNodeAddress->rVisited = true;
        }else{
            mNodeAddress->rVisited = false;
        }
    }

}


Node * GetNodeBaseAddress(int NodeName){
    int i;
    for(i=0;i<NodeIndexHead;i++){
        if(AllNodeList[i]->iNodeName == NodeName){
            return AllNodeList[i];
        }
    }
    return NULL;
}

int GetNodeDegree(int NodeName){
    Node* tmp = GetNodeBaseAddress(NodeName);
    int i=0;
    if(tmp!=NULL){
        tmp = tmp->iNextNode;
    }
    while(tmp!=NULL){
        i++;
        tmp=tmp->iNextNode;
    }
    return i;
}

int TotalNodeInGraph(){
    return NodeIndexHead;
}

int TotalEdgeInGraph(){
    return INVALID;
}


typedef struct smQueue{
    Node *smX;
    Node *smY;
    struct smQueue *next;
}smNode;


smNode *smFirstNode, *smLastNode, *tempNode;
bool firstTime = true;

void Enqueue(Node *valX, Node *valY){
    smNode *nde = malloc(1 * sizeof(smNode));
    if(firstTime){
        firstTime = false;
        smFirstNode = nde;
        smLastNode = nde;
        smLastNode->smX = valX;
        smLastNode->smY = valY;
        smLastNode->next = NULL;
        return;
    }
    smLastNode->next = nde;
    smLastNode = nde;
    smLastNode->smX = valX;
    smLastNode->smY = valY;
    smLastNode->next = NULL;

}


bool Dequeue(Node **smValueX, Node **smValueY){

    if(smFirstNode!=NULL){
        *smValueX = smFirstNode->smX;
        *smValueY = smFirstNode->smY;
        tempNode = smFirstNode->next;
        free(smFirstNode);
        smFirstNode = tempNode;
        if(smFirstNode==NULL){
            firstTime = true;
        }
        return true;
    }
    return false;
}


void BFS(int startNode,int startCost){

    Node *bfsTmpNode, *bfsTmpParentNode, *bfsGarbageNode,*bfsListTraversal;

    bfsTmpNode = GetNodeBaseAddress(startNode);
    if(bfsTmpNode==NULL) return;
    bfsTmpNode->rVisited = true;
    bfsTmpNode->rCost = startCost;
    bfsTmpNode->rPreviousNode = NULL;
    Enqueue(bfsTmpNode,NULL);

    while(Dequeue(&bfsTmpParentNode,&bfsGarbageNode)){
        bfsListTraversal = bfsTmpParentNode;

        while(1){
            bfsListTraversal = bfsListTraversal->iNextNode;
            if(bfsListTraversal==NULL) break;

            if(bfsTmpParentNode->rCost == 0)continue;

            bfsTmpNode = bfsListTraversal->bBaseAddress;
            if(bfsTmpNode->rVisited) continue;
            bfsTmpNode->rVisited = true;
            bfsTmpNode->rCost = bfsTmpParentNode->rCost - 1;
            bfsTmpNode->rPreviousNode = bfsTmpParentNode;
            Enqueue(bfsTmpNode,NULL);
        }
    }
}


void ClearBFSResult(){
    int i;
    for(i=0;i<NodeIndexHead;i++){
        AllNodeList[i]->rCost = INVALID;
        AllNodeList[i]->rPreviousNode = NULL;
        AllNodeList[i]->rVisited = false;
    }

}

void ClearGRAPH(){
    int i;
    for(i=0;i<NodeIndexHead;i++){
        AllNodeList[i]=NULL;
    }
    NodeIndexHead = 0;
} 6 more words
UVa