I am trying to use the BFS method to search through my graph and then determine if there is a path between my two nodes. I understand it and can implement it with a linked list, but I am just having trouble grasping it with a matrix instead.
I believe I am going wrong in my looping section, I feel like I am iterating on the wrong thing, or maybe comparing the wrong values. Thanks for any help.
Here is the code I have:
#include <iostream>
#include <queue>
#include <string.h>
#include <stack>
#include <list>
using namespace std;
class Graph{
private:
int total_routes;
int total_stations;
public:
int AdjMatrix[100][100];
Graph(int routes, int stations);
void addRoute(int from, int to, int weight);
void printGraph();
bool isRoute(int from, int to);
};
Graph::Graph(int routes, int stations)
{
for(int i = 0; i < stations; i++){
for(int j=0; j < stations; j++){
AdjMatrix[i][j]=0;
}
}
total_routes = routes;
total_stations = stations;
}
void Graph::printGraph(){
cout << "\n" << endl;
for(int i = 0; i < total_stations; i ++){
for(int j = 0; j < total_stations; j++){
cout << " " << AdjMatrix[i][j];
}
cout << endl;
}
}
void Graph::addRoute(int from, int to, int weight){
AdjMatrix[from][to] = weight;
}
bool Graph::isRoute(int from, int to){
bool route = false;
bool visited[total_stations] = {false};
queue<int> verticies;
if (from == to){
cout << "Going into if its the same node statement" << endl;
return true;
}
visited[from] = true;
verticies.push(from);
cout << "Testing if there is a route from " << from << " To " << to << endl;
while(!verticies.empty() && route == false ){
int current;
current = verticies.front();
verticies.pop();
cout << "Going into for Loop, with a current value of " << current << endl;
for ( int i = AdjMatrix[current][0]; i < total_stations ; i++ ){
if (i == to ){
route = true;
break;
}
if ( visited[i] == false){
visited[i] = true;
verticies.push(i);
}
}
}
return route;
}
int main() {
Graph newGraph(2,10); //10 stations(Nodes), 2 routes
newGraph.addRoute(0,1,10); //Route from 1 to 2, with a weight of 10.
newGraph.addRoute(2,9,1); //Route of 2 to 9, with a weight of 1.
newGraph.printGraph();
bool answer = newGraph.isRoute(3,9); //Should say no route...
if (answer){
cout << "There is a route!" << endl;
}
else{
cout << "There is no route!" << endl;
}
return 0;
}
It would be better to initialize AdjMatrix[i][j] with NULL
Then you can do
for ( int i = 0; i < total_stations ; i++ ){
if (AdjMatrix[current][i]!=NULL)
{
if (i == to ){
route = true;
break;
}
if ( visited[i] == false){
visited[i] = true;
verticies.push(i);
}
}
You should iterate over this way
for ( int i = 0; i < total_stations ; i++ )
and check whether
visited[i] == false && AdjMatrix[current][i] != 0
to push new vertices into the queue.
Related
i have created two functions for finding paths between two vertices in a adjacency matrix.
first function countPath run for each edge of source vertex;
void countPath(int s,int d){
int count=0;
for (int i = 0; i < V;i++){
if(visited[i]==0&&adj_mat[s][i]==1){
cout << s << " ";
searchForNode(i, d, &count);
}
}
cout << count << endl;
}
second function searchForNode searches the path for each edge of source node to destination vertex;
bool searchForNode(int i,int k,int *c){
if(i==k){
cout << "f" << i << endl;
return true;
}
int cnt = 0;
visited[i] = 1;
bool flag = false;
cout << i << " ";
for (int j = 0; j < V;j++){
if(visited[j]==0&&adj_mat[i][j]==1){
if(searchForNode(j,k,c)){
flag = true;
cnt++;
// return true;
}
}
}
if(flag==true){
*c = *c + cnt;
return true;
}
return false;
}
Can someone please help me. I am struggling to find in my code why the last value in column B always gets incremented by one. I have written some code since its an assignment due today. I also cant figure out why the last value in column B is not equal to 196 because in the reset function it sets all the values in the array to 196 . Any suggestion would be appreciated. Thank you in advance
#include <iostream> //includes cin cout
#include <iomanip>
using namespace std; //setting up the environment
const int NUMBER_OF_ROWS = 3;
const int NUMBER_OF_COLUMNS = 3;
void printAllSeats(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS]);
void reset(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS]);
void askForUsersSeat(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS], int &SeatCountNumber, bool &anyFreeSeats);
bool isFull(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS]);
bool isEmpty(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS]);
int main() { //main starts
int maxSeats;
int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS];
int SeatCountNumber = 0;
bool anyFreeSeats;
reset(seats);
anyFreeSeats = true;
SeatCountNumber = 0;
while (anyFreeSeats) {
printAllSeats(seats);
askForUsersSeat(seats, SeatCountNumber, anyFreeSeats);
}
system("pause");
return 0;
} //main ends
void printAllSeats(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS]) {
cout << endl;
cout << setw(10) << " - = Available R = Reserved\n\n";
for (int i = 0; i <= NUMBER_OF_ROWS; i++) {
cout << setw(15) << i << " ";
for (int j = 0; j < NUMBER_OF_COLUMNS; j++) {
if (i == 0) {
cout << " " << static_cast<char>(j + 65) << " ";
} else {
cout << " " << static_cast<char>(seats[i][j]) << " ";
}
}
cout << endl;
}
cout << endl;
}
void reset(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS]) {
//set all values in array to 196
for (int i = 0; i <= NUMBER_OF_ROWS; i++) {
for (int j = 0; j <= NUMBER_OF_COLUMNS; j++) {
seats[i][j] = 196;
}
}
}
void askForUsersSeat(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS], int &SeatCountNumber, bool &anyFreeSeats) {
int seatChoiceNumber;
char seatChoiceLetter;
int letter;
int maxSeats = NUMBER_OF_ROWS * NUMBER_OF_COLUMNS;
cout << "Seat (Row, Column): ";
cin >> seatChoiceNumber >> seatChoiceLetter;
letter = static_cast<int>(toupper(seatChoiceLetter));
if (((letter >= 65) && (letter < (65 + NUMBER_OF_COLUMNS))) && ((seatChoiceNumber > 0) && (seatChoiceNumber <= NUMBER_OF_ROWS))) {
if (seats[(seatChoiceNumber)][(letter - 65)] == 82) {
} else {
seats[(seatChoiceNumber)][(letter - 65)] = 82;
SeatCountNumber++; //this changes last value in column B for some reason
if (SeatCountNumber < maxSeats) {
anyFreeSeats = true;
}
else if (SeatCountNumber > maxSeats) {
printAllSeats(seats);
anyFreeSeats = false;
}
}
} else {
}
}
I kind of cleaned up the code a bit. It seems you found your answer in the comments, so I just did some indentation. Try and eliminate whitespaces in your code (mind you, the one I am putting here is not perfect either, but you get the point). Clean and easy to read code doesn't only make it better for you, but as you get higher up in the industry and other people begin reading and working on your code, having clean and easy to read code really helps :)
#include <iostream> //includes cin cout
#include <iomanip>
using namespace std; //setting up the environment
const int NUMBER_OF_ROWS = 3;
const int NUMBER_OF_COLUMNS = 3;
void printAllSeats(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS]);
void reset(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS]);
void askForUsersSeat(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS], int &SeatCountNumber, bool &anyFreeSeats);
bool isFull(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS]);
bool isEmpty(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS]);
int main()
{
int maxSeats;
int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS];
int SeatCountNumber = 0;
bool anyFreeSeats;
reset(seats);
anyFreeSeats = true;
SeatCountNumber = 0;
while (anyFreeSeats)
{
printAllSeats(seats);
askForUsersSeat(seats, SeatCountNumber, anyFreeSeats);
}
system("pause");
return 0;
} //main ends
void printAllSeats(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS])
{
cout << endl;
cout << setw(10) << " - = Available R = Reserved\n\n";
for (int i = 0; i <= NUMBER_OF_ROWS; i++)
{
cout << setw(15) << i << " ";
for (int j = 0; j < NUMBER_OF_COLUMNS; j++)
{
if (i == 0)
{
cout << " " << static_cast<char>(j + 65) << " ";
}
else
{
cout << " " << static_cast<char>(seats[i][j]) << " ";
}
}
cout << endl;
}
cout << endl;
}
void reset(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS])
{
//set all values in array to 196
for (int i = 0; i <= NUMBER_OF_ROWS; i++)
{
for (int j = 0; j <= NUMBER_OF_COLUMNS; j++)
{
seats[i][j] = 196;
}
}
}
void askForUsersSeat(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS], int &SeatCountNumber, bool &anyFreeSeats)
{
int seatChoiceNumber;
char seatChoiceLetter;
int letter;
int maxSeats = NUMBER_OF_ROWS * NUMBER_OF_COLUMNS;
cout << "Seat (Row, Column): ";
cin >> seatChoiceNumber >> seatChoiceLetter;
letter = static_cast<int>(toupper(seatChoiceLetter));
if (((letter >= 65) && (letter < (65 + NUMBER_OF_COLUMNS))) && ((seatChoiceNumber > 0) && (seatChoiceNumber <= NUMBER_OF_ROWS)))
{
if (seats[(seatChoiceNumber)][(letter - 65)] == 82)
{
}
else
{
seats[(seatChoiceNumber)][(letter - 65)] = 82;
SeatCountNumber++; //this changes last value in column B for some reason
if (SeatCountNumber < maxSeats)
{
anyFreeSeats = true;
}
else if (SeatCountNumber > maxSeats)
{
printAllSeats(seats);
anyFreeSeats = false;
}
}
}
else {
}
}
Note: Some more whitespaces could even come out but I generally like to have spaces after certain statements (personal preference).
I've been working on this for awhile and I have tried multiple different algorithms for the bubble sort that I have found online but none of them are working properly for me and I'm pretty close to giving up, but this is due tomorrow night. I'd really appreciate if someone could point out where im going wrong. I dont really understand this algorithm with the bool so ill try to find what i was trying before and edit it in
#include <iostream>
using namespace std;
void GetInfo(int[], int&);
void BubbleSort(int[], int);
void BinarySearch(int[], int);
int main()
{
int size;
int array[500];
GetInfo(array, size);
BubbleSort(array, size);
BinarySearch(array, size);
return 0;
}
void GetInfo(int array[], int& size)
{
cout << "Enter the number of naturals: ";
cin >> size;
cout << "Enter the natural numbers to sort: ";
for (int i = 0; i < size; i++)
{
cin >> array[i];
}
}
void BubbleSort(int array[], int size)
{
int temp;
bool check = true;
int end = 0;
while(check)
{
end++;
check = false;
for(int i = 0; i < size - end; i++)
{
if (array[i] > array[i+1]) //I'm positive this part is correct
{
temp = array[i];
array[i] = array[i+1];
array[i+1] = temp;
check = true;
}
}
}
cout << endl << "Numbers sorted in ascending order: " << endl;
for (int i = 0; i < size; i++)
{
cout << array[i] << ' ';
}
}
void BinarySearch(int array[], int size) //this doesnt work properly atm but
{ //should be good when the sort works
int index;
int top = size - 1;
int bottom = 0;
int middle = (top) / 2;
bool found = false;
int target;
cout << endl << "Enter the number to search: ";
cin >> target;
while (found == false)
{
if (target > array[middle])
{
bottom = middle + 1 ;
middle = ((top - bottom)/2) + bottom;
}
else if (target < array[middle])
{
top = middle - 1;
middle = ((top - bottom)/2) + bottom;
}
else
{
found = true;
index = middle;
}
}
cout << "Number " << target << " is found in position " << index << endl;
}
You might meant to swap a[i] with a[i+1] while you actually swapped a[size+1]
These lines are wrong:
array[i] = array[size+1];
array[size+1] = temp;
You need:
array[i] = array[i+1];
array[i+1] = temp;
This question already has answers here:
Bitset in C++, about continuously add
(2 answers)
Closed 8 years ago.
I'm trying to create a loop that changes the values in a boolean array so that it looks like the array is incrementing in binary values.
For example
1st iteration [0|0|0]
2nd iteration [0|0|1]
3rd iteration [0|1|0]
4th iteration [0|1|1]
etc.
This array is dynamic, however, and can be different sizes. So whatever loop I write would need to also work on an array with five elements instead of three.
Apologies for not having any starting code, but I've been frustrating myself with this for hours and still can't even come up with how to begin.
Try this. This may not be complete but you could do something similar
#include <iostream>
using namespace std;
void increment(bool* array, int len)
{
for (int i = len - 1; i >= 0; --i)
{
if ( ! array[i])
{
array[i] = true;
return;
}
array[i] = false;
}
}
int main()
{
bool* array = new bool[10];
for (int i = 0; i < 5; ++i)
{
increment(array, 10);
for (int i = 0; i < 10; ++i)
{
cout << (array[i] ? 1 : 0) << "|";
}
cout << endl;
}
return 0;
}
#include <iostream>
#include <cmath>
#include <memory>
using namespace std;
void ArrayIterate(int);
void printArray(bool*,int);
void ArrayIterate(int arraySize)
{
int decimal_value = 0;
int decimal_place_value = 0;
bool* boolArray = new bool(arraySize);
long double max_itr = pow(2,arraySize);
for (int i = 0; i < max_itr ; ++i)
{
decimal_value = i;
// set array values
for ( int k = arraySize - 1; k >= 0; --k)
{
decimal_place_value = pow(2,k);
if( decimal_value != 0 && decimal_value / decimal_place_value >= 1 )
{
boolArray[k] = true;
decimal_value -= decimal_place_value;
}
else
boolArray[k] = false;
}
printArray(boolArray,arraySize);
cout << " = " << i << endl; ;
}
delete boolArray;
return;
}
void printArray(bool* boolArray, int arraySize)
{
cout << "\t";
for(int i = arraySize - 1; i >= 0; --i)
cout << ((boolArray[i] == true)? 1 : 0) << " ";
return;
}
int main()
{
cout << "\n\n";
ArrayIterate(4);
cout << "\n\n" << endl;
return 0;
}
Im trying to build a minesweeper game and i keep getting a compiling error: lvalue required as left operand of assignment. only on these two lines:
#include <iostream>
#include <ctime>
using namespace std;
// ------------------------------------------------------
// class Cell
// represents one grid element in the Minesweeper game
// ------------------------------------------------------
class Cell {
public:
Cell();
void print();
void peek();
void unittest();
void setMined(bool);
bool getMined();
void setAdj(int);
private:
bool covered;
bool marked;
bool mined;
int adjcount;
};
// ------------------------
// functions for class Cell
// ------------------------
Cell::Cell(){
covered = true;
marked = false;
mined = false;
adjcount = 0;
// cout << "Creating a Cell" << endl;
}
void Cell::setAdj(int n){
adjcount = n;
}
bool Cell::getMined(){
return mined;
}
void Cell::setMined(bool b){
mined = b;
}
void Cell::print(){
if (marked) cout << " L ";
else {
if (covered) cout << " ? ";
else{
if (mined) cout << " # ";
else if (adjcount == 0) cout << " _ ";
else cout << " " << adjcount << " ";
}
}
}
void Cell::peek(){
if (mined) cout << " # ";
else if (adjcount == 0) cout << " _ ";
else cout << " " << adjcount << " ";
}
void Cell::unittest(){
print(); cout << endl;
covered = false;
print(); cout << endl;
adjcount = 4;
print(); cout << endl;
mined = true;
print(); cout << endl;
covered = true;
print(); cout << endl;
marked = true;
print(); cout << endl;
}
// -------------------------------------
// class Board
// this class represents a 2 dimensional
// array of Cell objects for the game
// of minesweeper
//--------------------------------------
class Board{
public:
Board();
void print();
void peek();
void adjacencycount();
void mixMined();
private:
static const int rows = 5;
static const int cols = 5;
Cell cells [rows][cols];
int mines;
};
// --------------------------
// functions for class Board
// --------------------------
Board::Board(){
mines = 6;
for(int i = 0; i < 1 ; i++){
for(int j = 0; j < mines; j++){
cells[i][j].setMined(true);
}
}
}
void Board::mixMined(){
int shuffle = 1000;
for(int i = 0; i < shuffle; i++){
int r1 = (rand()%rows);
int c1 = (rand()%cols);
int r2 = (rand()%rows);
int c2 = (rand()%cols);
if(r1 && c1 != r2 && c2){
bool temp = cells[r1][c1].getMined();
cells[r1][c1].getMined() = cells[r2][c2].getMined();
cells[r2][c2].getMined() = temp;
}
}
}
void Board::adjacencycount(){
for( int i = 0; i < rows; i++){
for( int j = 0; j < cols; j++){
if(!cells[i][j].getMined()){
int count = 0;
if (i-1 >= 0 && j-1 >= 0 && cells[i-1][j-1].getMined()) count++;
if (i-1 >= 0 && cells[i-1][j].getMined()) count++;
if (i-1 >= 0 && j+1 <= cols-1 && cells[i-1][j+1].getMined()) count++;
if (j-1 >= 0 && cells[i][j-1].getMined()) count++;
if (j+1 <= cols-1 && cells[i][j+1].getMined()) count++;
if (i+1 <= rows-1 && j-1 >= 0 && cells[i+1][j-1].getMined()) count++;
if (i+1 <= rows-1 && cells[i+1][j].getMined()) count++;
if (i+1 <= rows-1 && j+1 <= cols-1 && cells[i+1][j+1].getMined()) count++;
cells[i][j].setAdj(count);
// cout << count; -- for testing purposes
}
}
}
}
void Board::print(){
for (int i = 0; i < rows; i++){
for (int j = 0; j < cols; j++){
cells[i][j].print();
}
cout << endl << endl;
}
}
void Board::peek(){
for (int i = 0; i < rows; i++){
for (int j = 0; j < cols; j++){
cells[i][j].peek();
}
cout << endl << endl;
}
}
// -------------------------
// main function for testing
// -------------------------
int main(void) {
//Cell c;
//c.unittest();
srand(time(0));
Board b;
b.mixMined();
b.adjacencycount();
b.peek();
return 0;
}
I'm trying to get my cells to swap, so that the mines would randomize every new game. Ive searched around and couldn't find a solution to this. I added "==" but that function isn't going to do what i want it to.
++EDIT++ I'm sorry it did state lvalue required, i missed typed that
minesweeper.cpp: In member function ‘void Board::mixMined()’:
minesweeper.cpp:130: error: lvalue required as left operand of assignment
minesweeper.cpp:131: error: lvalue required as left operand of assignment
Thats the error that occurs.
I think getMined() is actually something like this:
bool getMined()
So you are trying to assign to rValue which is not possible
You might want to write some function like:
void setMined(bool m) and the use it like:
cells[r1][c1].setMined( cells[r2][c2].getMined() );