Grid Paths
Part of the Logic & Flow section of Coddy's R journey. Lesson 64 of 64.
Challenge
HardComplete count_paths(grid). grid is a matrix of 0s (open cells) and 1s (walls). A path starts at the top-left cell, ends at the bottom-right cell, moves only right or down, and never enters a wall. Return two lines: Paths: with the number of different paths, and Steps: with the number of moves in any path (all paths have the same length), or Steps: none when there is no path.
Build a matrix ways of the same size where each cell holds the number of paths that reach it: an open cell gets the sum of the cell above and the cell to its left, and a wall gets 0.
The supplied code reads the grid from one line: rows are separated by ; and the values of a row by ,. It prints each returned line.
Try it yourself
count_paths <- function(grid) {
# Write your code here
c("Paths: 0", "Steps: none")
}
# Supplied input/output code: keep it as it is
input <- suppressWarnings(readLines(file("stdin")))
rows <- strsplit(input[1], ";")[[1]]
grid <- matrix(as.numeric(unlist(strsplit(rows, ","))), nrow = length(rows), byrow = TRUE)
cat(count_paths(grid), sep = "\n")
All lessons in Logic & Flow
1Strings In Depth
Substrings with substr()Formatting with sprintf()Splitting and JoiningSearching StringsReplacing TextRecap - Username Builder4Matrices
Creating MatricesIndexing MatricesRow and Column SummariesMatrix ArithmeticRecap - Seating Chart2Key-Value Lookups
Named Vector LookupsChecking KeysAdding and Removing KeysLooping Over NamesRecap - Stock Desk3Sets and Counting
Unique ValuesSet OperationsMembership TestsCounting with table()Recap - Event Guests6Functions as Values
Anonymous FunctionsPassing FunctionsReturning FunctionsClosures with StateRecap - Discount Rules9Data Frames
Creating Data FramesColumns and RowsFiltering RowsAdding and SortingRecap - Sales Report12Project - Expense Tracker
Recording ExpensesTotal SpendingPractice on your own: Online R compiler