2
\$\begingroup\$

I have written code for graph traversal using adjacency matrices in an iterative approach. The code should print the graph in a DFS way.

#include <iostream>
using namespace std;
int main(){
    int n;
    cin>>n;
    int c[n][n];
    int i,j;
    for(i=0;i<n;i++){
        for(j=0;j<n;j++){
            cin>>c[i][j];
        }
    }
    int dfs[n];
    for(i=0;i<n;i++){
        dfs[i]=-1;
    }
    dfs[0]=1;
    j=1;
    for(i=0;i<n;i++){
        if(dfs[i]==1&&i>j)
        cout<<i;
        dfs[i]=1;
        while(c[i][j]!=0&&j<n&&i<n){
            if(dfs[j]==-1)
            {
                dfs[j]=1;
            }
            if(dfs[j]==1){
                cout<<j;
                j++;
            }
        }
    }
}

Is my code correct? If not, correct me. Can we decrease time complexity?

\$\endgroup\$
  • 1
    \$\begingroup\$ Welcome to Code Review! If you add sample input and output, you should get much better reviews. Also, make sure that you read How to ask a good question in our Help Center. \$\endgroup\$ – Edward Jun 5 '15 at 17:38
3
\$\begingroup\$

It's nearly impossible to tell what your code does because:

  1. The variable names are meaningless
  2. There are no prompts for the user to tell them what the inputs mean
  3. The output appears to just be a string of numbers with no apparent meaning

I can't tell you if it's correct or not (which is beyond the scope of Code Review anyway) because I can't tell what it's trying to do. In terms of trying to improve your code, I recommend changing the variable names from single letters or cryptic acronyms to full words, such as adjacencyMatrix and traversalList, or whatever they actually represent.

I recommend outputting some strings to tell the user what to input. Alternately, if this code is supposed to read its input from a file, then you should write code to read from a file instead of assuming it will come from standard in.

Finally, your output should say what it's outputting and have some sort of separators between the values, such as commas, spaces, or line endings. Again, if it's meant to be outputting to a file, then you should write code to write to a file rather than standard out.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.