Optimizing Graph class algorithmWhen should you use a class vs a struct in C++?What is the difference between old style and new style classes in Python?Are static class variables possible?What techniques can be used to define a class in JavaScript, and what are their trade-offs?Getting the class name of an instance?Call a parent class's method from child class in Python?Does Python have “private” variables in classes?Python class inherits objectWhat does “Could not find or load main class” mean?Convert graph to have outdegree 1 (except extra zero weight edges)

How do governments keep track of their issued currency?

Difference between > and >> when used with a named pipe

Share calendar details request from manager's manager

SOQL Not Recognizing Field?

Overlapping String-Blocks

Are there any important biographies of nobodies?

How to deal with apathetic co-worker?

How can "научись" mean "take it and keep trying"?

How can electric fields be used to detect cracks in metals?

Find the limit of a multiplying term function when n tends to infinity.

What is the fastest method to figure out which keys contain certain notes?

Universal hash functions with homomorphic XOR property

Is open-sourcing the code of a webapp not recommended?

What is the highest possible permanent AC at character creation?

Would the US government be able to hold control if all electronics were disabled for an indefinite amount of time?

What is wrong with this proof that symmetric matrices commute?

How to hide an urban landmark?

How does an ordinary object become radioactive?

Why doesn't Adrian Toomes give up Spider-Man's identity?

What do abbreviations in movie scripts stand for?

Motivation - or how can I get myself to do the work I know I need to?

A planet of ice and fire

What's up with this leaf?

Preventing employees from either switching to competitors or opening their own business



Optimizing Graph class algorithm


When should you use a class vs a struct in C++?What is the difference between old style and new style classes in Python?Are static class variables possible?What techniques can be used to define a class in JavaScript, and what are their trade-offs?Getting the class name of an instance?Call a parent class's method from child class in Python?Does Python have “private” variables in classes?Python class inherits objectWhat does “Could not find or load main class” mean?Convert graph to have outdegree 1 (except extra zero weight edges)






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








0















I've got the following assignment for one of my classes. My current solution is showed below the assignment text. I am finding the correct result but my code is too slow to give me the necessary points needed.



The Assignment



Josefine and her little sister is playing a game called Letter Labyrinth. In this game, a N times N matrix is filled with As and Bs (see example below). The challenge is to find the shortest path that leads from the top left corner to the lower right corner. The path must alternate between A's and B's, ie. when reading the letters on the path it should spell out ABABABA... The path can only go up/right/down/left. In the following example the shortest path has been marked with lower case letters.



aAaba
bBbBb
abaAa
ABBBb
AAAAa


As they find it difficult to determine if they have found the shortest path, they need you to write a program to verify this for them.



Input format



Line 1: The integer N
Line 2..N+1: The N times N matrix of letters (A or B) corresponding to the labyrinth.


Output format



Line 1: The number of letters on the shortest path from the top left corner to the lower right corner.


My code



First i've made a Graph class. Here i will primarily use the shortPath function of the class.



class Graph:
# Laver en graph, hvis intet input så laves en tom graph.
# Input et dict med hver verticy samt dens edges.
def __init__(self, gd=None):
if gd is None:
gd =
self.gd = gd

def genEdges(self):
edges = []
# Her er v vertecies og n er neighbours til hver edge.
for v in self.gd:
for n in self.gd[v]:
if n,v not in edges:
edges.append(v,n)
return edges

def addVert(self,v):
# Tilføjer vertex med tom liste af edges.
if v not in self.gd:
self.gd[v] = []

def addEdge(self, edges):
# Her skal edges være en liste med 2 verticies som skal forbindes.
self.gd[edges[0]].append(edges[1])
self.gd[edges[1]].append(edges[0])

def pVert(self):
return list(self.gd.keys())

def pEdges(self):
return self.genEdges()

def BFS(self, v):
# Laver dict til at tjekke om en verticy er besøgt
b =
for i in self.gd:
b[i] == False

b[v] = True

# Laver en que
q = []
q.append[v]

paths =

while q:
v = q.pop(0)
print(v)

for i in self.gd[v]:
if b[i] == False:
q.append(i)
b[i] = True

def shortPath(self, start, slut, path = list()):
# Laver en list som vejen til slut.
path = path + [start]
# Tjekker om start og slut er den samme
if start == slut:
return path

# Tjekker om start er i grafen
if start not in self.gd:
return None

# Laver en variabel til at gemme shortest path
sPath = []
for v in self.gd[start]:
if v not in path:
nPath = self.shortPath(v, slut, path)
if len(nPath) > 0:
if len(sPath) == 0 or len(nPath) < len(sPath):
sPath = nPath
return sPath


Afterwards ill create and use the graph class in the following code.



g = Graph()

N = int(input())

countA = 1
countB = 1

for i in range(0,N):
Line = list(input())

for j in range(0,len(Line)):
if Line[j] == "A":
Line[j] = "A" + str(countA)
countA += 1
elif Line[j] == "B":
Line[j] = "B" + str(countB)
countB += 1

# Tilføjer Vertecies
g.addVert(Line[j])

if Line[j][0] == "A":
if j > 0 and Line[j-1][0] == "B":
# Tilføjer Edges til venstre
g.addEdge([Line[j],Line[j-1]])
if Line[j][0] == "A":
if i > 0 and Line2[j][0] == "B":
g.addEdge([Line[j],Line2[j]])

if Line[j][0] == "B":
if j > 0 and Line[j-1][0] == "A":
# Tilføjer Edges til venstre
g.addEdge([Line[j],Line[j-1]])
if i > 0 and Line2[j][0] == "A":
g.addEdge([Line[j],Line2[j]])
# Tilføjer edges opad

if i == 0:
Start = Line[0]

if i == N-1:
End = Line[-1]

Line2 = Line


sp = g.shortPath(Start,End)
print(len(sp))


My problem is as described above that the code is too slow. If anyone knows a way to optimize it i would really appreciate it.



Thanks in advance.










share|improve this question




























    0















    I've got the following assignment for one of my classes. My current solution is showed below the assignment text. I am finding the correct result but my code is too slow to give me the necessary points needed.



    The Assignment



    Josefine and her little sister is playing a game called Letter Labyrinth. In this game, a N times N matrix is filled with As and Bs (see example below). The challenge is to find the shortest path that leads from the top left corner to the lower right corner. The path must alternate between A's and B's, ie. when reading the letters on the path it should spell out ABABABA... The path can only go up/right/down/left. In the following example the shortest path has been marked with lower case letters.



    aAaba
    bBbBb
    abaAa
    ABBBb
    AAAAa


    As they find it difficult to determine if they have found the shortest path, they need you to write a program to verify this for them.



    Input format



    Line 1: The integer N
    Line 2..N+1: The N times N matrix of letters (A or B) corresponding to the labyrinth.


    Output format



    Line 1: The number of letters on the shortest path from the top left corner to the lower right corner.


    My code



    First i've made a Graph class. Here i will primarily use the shortPath function of the class.



    class Graph:
    # Laver en graph, hvis intet input så laves en tom graph.
    # Input et dict med hver verticy samt dens edges.
    def __init__(self, gd=None):
    if gd is None:
    gd =
    self.gd = gd

    def genEdges(self):
    edges = []
    # Her er v vertecies og n er neighbours til hver edge.
    for v in self.gd:
    for n in self.gd[v]:
    if n,v not in edges:
    edges.append(v,n)
    return edges

    def addVert(self,v):
    # Tilføjer vertex med tom liste af edges.
    if v not in self.gd:
    self.gd[v] = []

    def addEdge(self, edges):
    # Her skal edges være en liste med 2 verticies som skal forbindes.
    self.gd[edges[0]].append(edges[1])
    self.gd[edges[1]].append(edges[0])

    def pVert(self):
    return list(self.gd.keys())

    def pEdges(self):
    return self.genEdges()

    def BFS(self, v):
    # Laver dict til at tjekke om en verticy er besøgt
    b =
    for i in self.gd:
    b[i] == False

    b[v] = True

    # Laver en que
    q = []
    q.append[v]

    paths =

    while q:
    v = q.pop(0)
    print(v)

    for i in self.gd[v]:
    if b[i] == False:
    q.append(i)
    b[i] = True

    def shortPath(self, start, slut, path = list()):
    # Laver en list som vejen til slut.
    path = path + [start]
    # Tjekker om start og slut er den samme
    if start == slut:
    return path

    # Tjekker om start er i grafen
    if start not in self.gd:
    return None

    # Laver en variabel til at gemme shortest path
    sPath = []
    for v in self.gd[start]:
    if v not in path:
    nPath = self.shortPath(v, slut, path)
    if len(nPath) > 0:
    if len(sPath) == 0 or len(nPath) < len(sPath):
    sPath = nPath
    return sPath


    Afterwards ill create and use the graph class in the following code.



    g = Graph()

    N = int(input())

    countA = 1
    countB = 1

    for i in range(0,N):
    Line = list(input())

    for j in range(0,len(Line)):
    if Line[j] == "A":
    Line[j] = "A" + str(countA)
    countA += 1
    elif Line[j] == "B":
    Line[j] = "B" + str(countB)
    countB += 1

    # Tilføjer Vertecies
    g.addVert(Line[j])

    if Line[j][0] == "A":
    if j > 0 and Line[j-1][0] == "B":
    # Tilføjer Edges til venstre
    g.addEdge([Line[j],Line[j-1]])
    if Line[j][0] == "A":
    if i > 0 and Line2[j][0] == "B":
    g.addEdge([Line[j],Line2[j]])

    if Line[j][0] == "B":
    if j > 0 and Line[j-1][0] == "A":
    # Tilføjer Edges til venstre
    g.addEdge([Line[j],Line[j-1]])
    if i > 0 and Line2[j][0] == "A":
    g.addEdge([Line[j],Line2[j]])
    # Tilføjer edges opad

    if i == 0:
    Start = Line[0]

    if i == N-1:
    End = Line[-1]

    Line2 = Line


    sp = g.shortPath(Start,End)
    print(len(sp))


    My problem is as described above that the code is too slow. If anyone knows a way to optimize it i would really appreciate it.



    Thanks in advance.










    share|improve this question
























      0












      0








      0








      I've got the following assignment for one of my classes. My current solution is showed below the assignment text. I am finding the correct result but my code is too slow to give me the necessary points needed.



      The Assignment



      Josefine and her little sister is playing a game called Letter Labyrinth. In this game, a N times N matrix is filled with As and Bs (see example below). The challenge is to find the shortest path that leads from the top left corner to the lower right corner. The path must alternate between A's and B's, ie. when reading the letters on the path it should spell out ABABABA... The path can only go up/right/down/left. In the following example the shortest path has been marked with lower case letters.



      aAaba
      bBbBb
      abaAa
      ABBBb
      AAAAa


      As they find it difficult to determine if they have found the shortest path, they need you to write a program to verify this for them.



      Input format



      Line 1: The integer N
      Line 2..N+1: The N times N matrix of letters (A or B) corresponding to the labyrinth.


      Output format



      Line 1: The number of letters on the shortest path from the top left corner to the lower right corner.


      My code



      First i've made a Graph class. Here i will primarily use the shortPath function of the class.



      class Graph:
      # Laver en graph, hvis intet input så laves en tom graph.
      # Input et dict med hver verticy samt dens edges.
      def __init__(self, gd=None):
      if gd is None:
      gd =
      self.gd = gd

      def genEdges(self):
      edges = []
      # Her er v vertecies og n er neighbours til hver edge.
      for v in self.gd:
      for n in self.gd[v]:
      if n,v not in edges:
      edges.append(v,n)
      return edges

      def addVert(self,v):
      # Tilføjer vertex med tom liste af edges.
      if v not in self.gd:
      self.gd[v] = []

      def addEdge(self, edges):
      # Her skal edges være en liste med 2 verticies som skal forbindes.
      self.gd[edges[0]].append(edges[1])
      self.gd[edges[1]].append(edges[0])

      def pVert(self):
      return list(self.gd.keys())

      def pEdges(self):
      return self.genEdges()

      def BFS(self, v):
      # Laver dict til at tjekke om en verticy er besøgt
      b =
      for i in self.gd:
      b[i] == False

      b[v] = True

      # Laver en que
      q = []
      q.append[v]

      paths =

      while q:
      v = q.pop(0)
      print(v)

      for i in self.gd[v]:
      if b[i] == False:
      q.append(i)
      b[i] = True

      def shortPath(self, start, slut, path = list()):
      # Laver en list som vejen til slut.
      path = path + [start]
      # Tjekker om start og slut er den samme
      if start == slut:
      return path

      # Tjekker om start er i grafen
      if start not in self.gd:
      return None

      # Laver en variabel til at gemme shortest path
      sPath = []
      for v in self.gd[start]:
      if v not in path:
      nPath = self.shortPath(v, slut, path)
      if len(nPath) > 0:
      if len(sPath) == 0 or len(nPath) < len(sPath):
      sPath = nPath
      return sPath


      Afterwards ill create and use the graph class in the following code.



      g = Graph()

      N = int(input())

      countA = 1
      countB = 1

      for i in range(0,N):
      Line = list(input())

      for j in range(0,len(Line)):
      if Line[j] == "A":
      Line[j] = "A" + str(countA)
      countA += 1
      elif Line[j] == "B":
      Line[j] = "B" + str(countB)
      countB += 1

      # Tilføjer Vertecies
      g.addVert(Line[j])

      if Line[j][0] == "A":
      if j > 0 and Line[j-1][0] == "B":
      # Tilføjer Edges til venstre
      g.addEdge([Line[j],Line[j-1]])
      if Line[j][0] == "A":
      if i > 0 and Line2[j][0] == "B":
      g.addEdge([Line[j],Line2[j]])

      if Line[j][0] == "B":
      if j > 0 and Line[j-1][0] == "A":
      # Tilføjer Edges til venstre
      g.addEdge([Line[j],Line[j-1]])
      if i > 0 and Line2[j][0] == "A":
      g.addEdge([Line[j],Line2[j]])
      # Tilføjer edges opad

      if i == 0:
      Start = Line[0]

      if i == N-1:
      End = Line[-1]

      Line2 = Line


      sp = g.shortPath(Start,End)
      print(len(sp))


      My problem is as described above that the code is too slow. If anyone knows a way to optimize it i would really appreciate it.



      Thanks in advance.










      share|improve this question














      I've got the following assignment for one of my classes. My current solution is showed below the assignment text. I am finding the correct result but my code is too slow to give me the necessary points needed.



      The Assignment



      Josefine and her little sister is playing a game called Letter Labyrinth. In this game, a N times N matrix is filled with As and Bs (see example below). The challenge is to find the shortest path that leads from the top left corner to the lower right corner. The path must alternate between A's and B's, ie. when reading the letters on the path it should spell out ABABABA... The path can only go up/right/down/left. In the following example the shortest path has been marked with lower case letters.



      aAaba
      bBbBb
      abaAa
      ABBBb
      AAAAa


      As they find it difficult to determine if they have found the shortest path, they need you to write a program to verify this for them.



      Input format



      Line 1: The integer N
      Line 2..N+1: The N times N matrix of letters (A or B) corresponding to the labyrinth.


      Output format



      Line 1: The number of letters on the shortest path from the top left corner to the lower right corner.


      My code



      First i've made a Graph class. Here i will primarily use the shortPath function of the class.



      class Graph:
      # Laver en graph, hvis intet input så laves en tom graph.
      # Input et dict med hver verticy samt dens edges.
      def __init__(self, gd=None):
      if gd is None:
      gd =
      self.gd = gd

      def genEdges(self):
      edges = []
      # Her er v vertecies og n er neighbours til hver edge.
      for v in self.gd:
      for n in self.gd[v]:
      if n,v not in edges:
      edges.append(v,n)
      return edges

      def addVert(self,v):
      # Tilføjer vertex med tom liste af edges.
      if v not in self.gd:
      self.gd[v] = []

      def addEdge(self, edges):
      # Her skal edges være en liste med 2 verticies som skal forbindes.
      self.gd[edges[0]].append(edges[1])
      self.gd[edges[1]].append(edges[0])

      def pVert(self):
      return list(self.gd.keys())

      def pEdges(self):
      return self.genEdges()

      def BFS(self, v):
      # Laver dict til at tjekke om en verticy er besøgt
      b =
      for i in self.gd:
      b[i] == False

      b[v] = True

      # Laver en que
      q = []
      q.append[v]

      paths =

      while q:
      v = q.pop(0)
      print(v)

      for i in self.gd[v]:
      if b[i] == False:
      q.append(i)
      b[i] = True

      def shortPath(self, start, slut, path = list()):
      # Laver en list som vejen til slut.
      path = path + [start]
      # Tjekker om start og slut er den samme
      if start == slut:
      return path

      # Tjekker om start er i grafen
      if start not in self.gd:
      return None

      # Laver en variabel til at gemme shortest path
      sPath = []
      for v in self.gd[start]:
      if v not in path:
      nPath = self.shortPath(v, slut, path)
      if len(nPath) > 0:
      if len(sPath) == 0 or len(nPath) < len(sPath):
      sPath = nPath
      return sPath


      Afterwards ill create and use the graph class in the following code.



      g = Graph()

      N = int(input())

      countA = 1
      countB = 1

      for i in range(0,N):
      Line = list(input())

      for j in range(0,len(Line)):
      if Line[j] == "A":
      Line[j] = "A" + str(countA)
      countA += 1
      elif Line[j] == "B":
      Line[j] = "B" + str(countB)
      countB += 1

      # Tilføjer Vertecies
      g.addVert(Line[j])

      if Line[j][0] == "A":
      if j > 0 and Line[j-1][0] == "B":
      # Tilføjer Edges til venstre
      g.addEdge([Line[j],Line[j-1]])
      if Line[j][0] == "A":
      if i > 0 and Line2[j][0] == "B":
      g.addEdge([Line[j],Line2[j]])

      if Line[j][0] == "B":
      if j > 0 and Line[j-1][0] == "A":
      # Tilføjer Edges til venstre
      g.addEdge([Line[j],Line[j-1]])
      if i > 0 and Line2[j][0] == "A":
      g.addEdge([Line[j],Line2[j]])
      # Tilføjer edges opad

      if i == 0:
      Start = Line[0]

      if i == N-1:
      End = Line[-1]

      Line2 = Line


      sp = g.shortPath(Start,End)
      print(len(sp))


      My problem is as described above that the code is too slow. If anyone knows a way to optimize it i would really appreciate it.



      Thanks in advance.







      python class






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Mar 24 at 17:19









      Markus SørensenMarkus Sørensen

      33




      33






















          1 Answer
          1






          active

          oldest

          votes


















          0














          Your code looks way more complicated to me, solving this problem with DFS is good aapproach, but I think you have unnecessary loops in your implementation.
          Pseudo code:



          import Queue
          # storeing edges
          Class Edge(i,j):
          isVisited
          distance = -1
          i
          j
          char
          # main function to call
          DFS(input):
          maxIndex = getN()
          q = Queue.Queue()
          edgeMatrix = initNtimesNMartixWithNulls()
          end = False
          q.put(edgeMartix[0][0];
          for i in range(0,N):
          for(j in range(0,N):
          char = someFunc(input,i,j)
          edgeMartix[i][j] = Edge(i,j)
          while not q.empty() and not end:
          e = q.get()
          end = addElement(q, e.i +1, e.j, q.char, q.distance) or end
          end = addElement(q, e.i -1, e.j, q.char, q.distance) or end
          end = addElement(q, e.i, e.j +1, q.char,q.distance) or end
          end = addElement(q, e.i, e.i -1, q.char, q.distance) or end
          return edgeMartix[N-1][N-1]

          addElement(edgeMartix, q,i,j,maxIndex, char, dist):
          if(i < 0 or i > maxIndex or j < 0 or i > maxIndex):
          return False
          e = edgeMartix[i][j]
          if (not e.isVisited and e.char != char):
          e.isVisited = True
          e.distance = distance + 1
          q.put(e)
          if (i == max and j == max ) :
          return True
          return False





          share|improve this answer























            Your Answer






            StackExchange.ifUsing("editor", function ()
            StackExchange.using("externalEditor", function ()
            StackExchange.using("snippets", function ()
            StackExchange.snippets.init();
            );
            );
            , "code-snippets");

            StackExchange.ready(function()
            var channelOptions =
            tags: "".split(" "),
            id: "1"
            ;
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function()
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled)
            StackExchange.using("snippets", function()
            createEditor();
            );

            else
            createEditor();

            );

            function createEditor()
            StackExchange.prepareEditor(
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader:
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            ,
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            );



            );













            draft saved

            draft discarded


















            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55326427%2foptimizing-graph-class-algorithm%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            0














            Your code looks way more complicated to me, solving this problem with DFS is good aapproach, but I think you have unnecessary loops in your implementation.
            Pseudo code:



            import Queue
            # storeing edges
            Class Edge(i,j):
            isVisited
            distance = -1
            i
            j
            char
            # main function to call
            DFS(input):
            maxIndex = getN()
            q = Queue.Queue()
            edgeMatrix = initNtimesNMartixWithNulls()
            end = False
            q.put(edgeMartix[0][0];
            for i in range(0,N):
            for(j in range(0,N):
            char = someFunc(input,i,j)
            edgeMartix[i][j] = Edge(i,j)
            while not q.empty() and not end:
            e = q.get()
            end = addElement(q, e.i +1, e.j, q.char, q.distance) or end
            end = addElement(q, e.i -1, e.j, q.char, q.distance) or end
            end = addElement(q, e.i, e.j +1, q.char,q.distance) or end
            end = addElement(q, e.i, e.i -1, q.char, q.distance) or end
            return edgeMartix[N-1][N-1]

            addElement(edgeMartix, q,i,j,maxIndex, char, dist):
            if(i < 0 or i > maxIndex or j < 0 or i > maxIndex):
            return False
            e = edgeMartix[i][j]
            if (not e.isVisited and e.char != char):
            e.isVisited = True
            e.distance = distance + 1
            q.put(e)
            if (i == max and j == max ) :
            return True
            return False





            share|improve this answer



























              0














              Your code looks way more complicated to me, solving this problem with DFS is good aapproach, but I think you have unnecessary loops in your implementation.
              Pseudo code:



              import Queue
              # storeing edges
              Class Edge(i,j):
              isVisited
              distance = -1
              i
              j
              char
              # main function to call
              DFS(input):
              maxIndex = getN()
              q = Queue.Queue()
              edgeMatrix = initNtimesNMartixWithNulls()
              end = False
              q.put(edgeMartix[0][0];
              for i in range(0,N):
              for(j in range(0,N):
              char = someFunc(input,i,j)
              edgeMartix[i][j] = Edge(i,j)
              while not q.empty() and not end:
              e = q.get()
              end = addElement(q, e.i +1, e.j, q.char, q.distance) or end
              end = addElement(q, e.i -1, e.j, q.char, q.distance) or end
              end = addElement(q, e.i, e.j +1, q.char,q.distance) or end
              end = addElement(q, e.i, e.i -1, q.char, q.distance) or end
              return edgeMartix[N-1][N-1]

              addElement(edgeMartix, q,i,j,maxIndex, char, dist):
              if(i < 0 or i > maxIndex or j < 0 or i > maxIndex):
              return False
              e = edgeMartix[i][j]
              if (not e.isVisited and e.char != char):
              e.isVisited = True
              e.distance = distance + 1
              q.put(e)
              if (i == max and j == max ) :
              return True
              return False





              share|improve this answer

























                0












                0








                0







                Your code looks way more complicated to me, solving this problem with DFS is good aapproach, but I think you have unnecessary loops in your implementation.
                Pseudo code:



                import Queue
                # storeing edges
                Class Edge(i,j):
                isVisited
                distance = -1
                i
                j
                char
                # main function to call
                DFS(input):
                maxIndex = getN()
                q = Queue.Queue()
                edgeMatrix = initNtimesNMartixWithNulls()
                end = False
                q.put(edgeMartix[0][0];
                for i in range(0,N):
                for(j in range(0,N):
                char = someFunc(input,i,j)
                edgeMartix[i][j] = Edge(i,j)
                while not q.empty() and not end:
                e = q.get()
                end = addElement(q, e.i +1, e.j, q.char, q.distance) or end
                end = addElement(q, e.i -1, e.j, q.char, q.distance) or end
                end = addElement(q, e.i, e.j +1, q.char,q.distance) or end
                end = addElement(q, e.i, e.i -1, q.char, q.distance) or end
                return edgeMartix[N-1][N-1]

                addElement(edgeMartix, q,i,j,maxIndex, char, dist):
                if(i < 0 or i > maxIndex or j < 0 or i > maxIndex):
                return False
                e = edgeMartix[i][j]
                if (not e.isVisited and e.char != char):
                e.isVisited = True
                e.distance = distance + 1
                q.put(e)
                if (i == max and j == max ) :
                return True
                return False





                share|improve this answer













                Your code looks way more complicated to me, solving this problem with DFS is good aapproach, but I think you have unnecessary loops in your implementation.
                Pseudo code:



                import Queue
                # storeing edges
                Class Edge(i,j):
                isVisited
                distance = -1
                i
                j
                char
                # main function to call
                DFS(input):
                maxIndex = getN()
                q = Queue.Queue()
                edgeMatrix = initNtimesNMartixWithNulls()
                end = False
                q.put(edgeMartix[0][0];
                for i in range(0,N):
                for(j in range(0,N):
                char = someFunc(input,i,j)
                edgeMartix[i][j] = Edge(i,j)
                while not q.empty() and not end:
                e = q.get()
                end = addElement(q, e.i +1, e.j, q.char, q.distance) or end
                end = addElement(q, e.i -1, e.j, q.char, q.distance) or end
                end = addElement(q, e.i, e.j +1, q.char,q.distance) or end
                end = addElement(q, e.i, e.i -1, q.char, q.distance) or end
                return edgeMartix[N-1][N-1]

                addElement(edgeMartix, q,i,j,maxIndex, char, dist):
                if(i < 0 or i > maxIndex or j < 0 or i > maxIndex):
                return False
                e = edgeMartix[i][j]
                if (not e.isVisited and e.char != char):
                e.isVisited = True
                e.distance = distance + 1
                q.put(e)
                if (i == max and j == max ) :
                return True
                return False






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Mar 24 at 18:07









                venetriusvenetrius

                111




                111





























                    draft saved

                    draft discarded
















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid


                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.

                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function ()
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55326427%2foptimizing-graph-class-algorithm%23new-answer', 'question_page');

                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

                    Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

                    Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript