Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 201919

How to find all possible "continuous" paths of a matrix / network / graph in R

$
0
0

I am interested in determining all of the possible "continuous" paths of an NxN matrix in R and returning their result. By "continuous" I mean that we can travel without lifting up your pencil/digit. That is, we can move up, down, left, right, or diagonally.

To make this concrete, let's use a 3x3 matrix example:

mat_3x3 <- matrix(LETTERS[1:9], ncol = 3, byrow = TRUE)
mat_3x3
#      [,1] [,2] [,3]
# [1,] "A""B""C" 
# [2,] "D""E""F" 
# [3,] "G""H""I"

This means we have the following valid and invalid paths:

valid and invalid paths

Some considerations:

  • The start position does not need to be position A (1, 1).
  • We cannot "double-back" or touch the same cell multiple times.
  • Short paths are possible (e.g. A -> B -> C is a valid path; likewise, A -> E -> I) -- that is, we do not need to pass through all the nodes.

If there is a package or concept that facilitates, please advise (most of the graph traversal packages I have seen are more "graph" than "matrix"). I'd imagine dynamic programming or recursion is probably of use here, but I am not sure how to start.


I believe the answer to the 2X2 case could be 60 per the following solution for one cell with paths = 15; 15 * 4 = 60:

2x2 case for one cell

However, things escalate quickly for a 3x3, 4x4, case...no longer just corners, the addition of "center" squares, etc...


If we think about this problem as more of a graph or network, we have the following for the 3X3 case:

network or graph visualization

Why though? I am just genuinely interested in this problem and find it fascinating. I'd like to understand how to program it in R, but I'd consider other answers if they exist (then perhaps translate them to R). It started as a thought experiment thinking about a "game" where you you slide your finger on a touch screen to create words from the string of characters. Rather than minimum cost, we'd like to maximize score -- using a Z scores more points than an E like in Scrabble, etc. But I suppose this has interesting applications in social networks, graph theory, transportation optimization, and other domains.


Viewing all articles
Browse latest Browse all 201919

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>